EDIT: forgot to include my environment info... Win7x64, RubyInstaller Ruby v1.9.1-p378
EDIT 2: just updated to v1.9.1, patch 429, and still getting this same error.
Edit 3: running this same code in Ruby v1.8.7, patch 249, works fine. so it's v1.9.1 that broke it, apparently.
I'm new to using ERB and the samples i could find are... ummm... less than helpful... having played around with ERB for about an hour, I got some basic examples working (finally), but I have no idea why this doesn't work...
require 'ostruct'
require 'erb'
data = {:bar => "bar"}
vars = OpenStruct.new(data)
template = "foo "
erb = ERB.new(template)
vars_binding = vars.send(:binding)
puts erb.result(vars_binding)
this code produces the following error:
irb(main):007:0> puts erb.result(vars_binding) NameError: undefined local variable or method `bar' for main:Object from (erb):1 from C:/Ruby/v1.9.1/lib/ruby/1.9.1/erb.rb:753:in `eval' from C:/Ruby/v1.9.1/lib/ruby/1.9.1/erb.rb:753:in `result' from (irb):7 from C:/Ruby/v1.9.1/bin/irb:12:in `'
why is it looking at the main:Object
binding? I told it to use the binding from the OpenStruct by passing in vars_binding
can someone fill me in on why it doesn't work, and help me get it to work?
What's your environment look like? This code worked for me (I just changed the string "bar" to "baz" to disambiguate in my brain, and added it to the template):
When I run it, I get:
Under 1.8.7 on OSX:
The problem is where the binding is being executed. The 1.8.7-way
obj.send(:binding)
does not work anymore (see issue2161), the environment must be the object itself. So useinstance_eval
:More about this issue in this answer.
Looks like this does not work with higher ruby versions
with ruby 2.1.1
with ruby 1.9.3
So it gives error but still works in 1.9.3 and all the versions below 1.9.3.
Fix to Problem:
I stumbled upon this question when encountering the same type of error with similar code in Ruby 1.9.2.
I'm new to Ruby so I can't explain what is happening. I continued to search online and found this blog post that has an approach that seems to work. After modifying your example to incorporate this approach I end up with the following, working, code:
Additional Information:
When the code is run thru the IRB, I get: