tags:

views:

49

answers:

1

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?

A: 

Hi Derick -

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):

require 'ostruct'
require 'erb'

data = {:bar => "baz"}
vars = OpenStruct.new(data)

template = "foo <%= bar %>"
erb = ERB.new(template)

vars_binding = vars.send(:binding)
puts erb.result(vars_binding)

When I run it, I get:

defeateds-MacBook-Pro:Desktop defeated$ ruby erb.rb 
foo baz

Under 1.8.7 on OSX:

defeateds-MacBook-Pro:Desktop defeated$ ruby -v
ruby 1.8.7 (2009-06-08 patchlevel 173) [universal-darwin10.0]
defeated