Maxim Maximov
Maxim Maximov

Reputation: 23

Ruby ERB render and def function

I got an strange issue with my experiments with ERB. Here what code do I have:

# cat ./services_lbs2.erb
<%= def renderVip(description, template)
puts "zxc dfg"
end
%>
# locally and remote
Printing: <%= renderVip('123','456') %>

And here what I am getting in the irb:

irb(main):034:0> @template=File.read('./services_lbs2.erb')
=> "<%= def renderVip(description, template)\nputs \"zxc dfg\"\nend\n%>\n# locally and remotely monitored (all externals)\nPrinting: <%= renderVip('123','456') %>\n"
irb(main):035:0> zxc = ERB.new(@template,nil, "-")
=> #<ERB:0x00000000068d4d88 @safe_level=nil, @src="#coding:US-ASCII\n_erbout = String.new; _erbout.concat(( def renderVip(description, template)\nputs \"zxc dfg\"\nend\n).to_s); _erbout.concat \"\\n# locally and remotely monitored (all externals)\\nPrinting: \"\n\n; _erbout.concat(( renderVip('123','456') ).to_s); _erbout.concat \"\\n\"\n; _erbout.force_encoding(__ENCODING__)", @encoding=#<Encoding:US-ASCII>, @frozen_string=nil, @filename=nil, @lineno=0>
irb(main):036:0> zxc.result(binding)
zxc dfg
=> "renderVip\n# locally and remotely monitored (all externals)\nPrinting: \n"

I could not get the output like:

# locally and remotely monitored (all externals)\nPrinting: zxc dfg\n

Why is it so and how it can be fixed?

Thanks!

Upvotes: 0

Views: 463

Answers (1)

Abdul Rehman
Abdul Rehman

Reputation: 742

The return value puts function is nil so in your case, the method will return nil.

So after execution nil is being appended inside the body tag. For this to work change it to

<% 
  def renderVip(description, template)
    "zxc dfg"
  end
%>

Upvotes: 2

Related Questions