为什么这个绑定不起作用

时间:2017-01-19 10:17:03

标签: ruby binding metaprogramming erb

我有这段代码:

require 'erb'
ab = 2 + 2
class Greeter
  def self.render(template)

    ERB.new(template).result(TOPLEVEL_BINDING)
  end
end

p Greeter.render("Hi <%= ab %>")

我得到undefined local variable or method 'ab' for main:Object。但是,当我将其更改为ab作为实例变量时,一切正常:

@ab = 2 + 2
class Greeter
  def self.render(template)

    ERB.new(template).result(TOPLEVEL_BINDING)
  end
end

p Greeter.render("Hi <%= @ab %>") # Hi 4

据我所知,TOPLEVEL_BINDING包含顶层的所有绑定,也包括局部变量。为什么abTOPLEVEL_BINDING作为userId的一部分而被捕获?

1 个答案:

答案 0 :(得分:4)

结果为TOPLEVEL_BINDING的人不是Hi 4

@ab = 2 + 2
class Greeter
  def self.render(template)
    ERB.new(template).result # NO binding at all
  end
end

p Greeter.render("Hi <%= @ab %>") # Still "Hi 4"

使用新的本地变量,TOPLEVEL_BINDING 永远不会更新

TOPLEVEL_BINDING.local_variables
#⇒ [:title] # it’s pry-related bullshit
a = 3.14
TOPLEVEL_BINDING.local_variables
#⇒ [:title] # no trace of `a`

what TOPLEVEL_BINDING is上的答案很好。