编辑:忘记包括我的环境信息… Win7x64,RubyInstaller Ruby v1.9.1-p378
编辑2:刚刚更新到v1.9.1,补丁429,并仍然得到同样的错误.
编辑3:在Ruby v1.8.7,补丁249中运行相同的代码,工作正常.所以它是v1.9.1打破了,显然.
我是新来使用ERB,我可以找到的样本是…嗯…不太有帮助…在ERB上玩了大约一个小时,我有一些基本的例子(最后),但我有不知道为什么这不工作…
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)
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 `'
为什么要看main:对象绑定?我告诉它通过传递vars_binding来使用OpenStruct的绑定
有人可以填补我为什么不起作用,并帮我让它上班吗?
解决方法
解决问题:
在Ruby 1.9.2中遇到相似类型的错误时,我偶然发现了这个问题.
我是Ruby的新手,所以我无法解释发生了什么.我继续在线搜索,发现this blog post有一种似乎有效的方法.在修改你的例子以纳入这种方法之后,我最终得到以下的工作代码:
require 'ostruct' require 'erb' class ErbBinding < OpenStruct def get_binding return binding() end end data = {:bar => "baz"} vars = ErbBinding.new(data) template = "foo <%= bar %>" erb = ERB.new(template) vars_binding = vars.send(:get_binding) puts erb.result(vars_binding)
附加信息:
当代码通过IRB运行时,我得到:
require 'ostruct' => true require 'erb' => true class ErbBinding < OpenStruct def get_binding return binding() end end => nil data = {:bar => "baz"} => {:bar=>"baz"} vars = ErbBinding.new(data) => #<ErbBinding bar="baz"> template = "foo <%= bar %>" => "foo <%= bar %>" erb = ERB.new(template) => #<ERB:0x2b73370 @safe_level=nil,@src="#coding:IBM437\n_erbout = ''; _erbout.concat \"foo \"; _erbout.concat(( bar ).to_s); _erbout.force_encoding(__ENCODING__)",@enc=#<Encoding:IBM437>,@filename=nil> vars_binding = vars.send(:get_binding) => #<Binding:0x2b6d418> puts erb.result(vars_binding) foo baz => nil