这里的(有些脆弱)黑客:
# caller_binding.rb
TRACE_STACK = []
VERSION_OFFSET = { "1.8.6" => -3, "1.9.1" => -2 }[RUBY_VERSION]
def caller_binding(skip=1)
TRACE_STACK[ VERSION_OFFSET - skip ][:binding]
end
set_trace_func(lambda do |event, file, line, id, binding, classname|
item = {:event=>event,:file=>file,:line=>line,:id=>id,:binding=>binding,:classname=>classname}
#p item
case(event)
when 'line'
TRACE_STACK.push(item) if TRACE_STACK.empty?
when /\b(?:(?:c-)?call|class)\b/
TRACE_STACK.push(item)
when /\b(?:(?:c-)?return|end|raise)\b/
TRACE_STACK.pop
end
end)
这适用于你的榜样,但我还没有太多别的
require 'caller_binding'
class A
def some_method
x = 123
nonexistent_method
end
def method_missing(method, *args, &block)
b = caller_binding
eval "puts x", b
end
end
x = 456
A.new.some_method #=> prints 123
A.new.nonexistent_method #=> prints 456
当然,这韩元测试它如果绑定没有定义你正在评估的变量,那么这种方法就行不通,但这是绑定的一个普遍问题。如果一个变量没有定义,它不知道它是什么。
require 'caller_binding'
def show_x(b)
begin
eval <<-SCRIPT, b
puts "x = \#{x}"
SCRIPT
rescue => e
puts e
end
end
def y
show_x(caller_binding)
end
def ex1
y #=> prints "undefined local variable or method `x' for main:Object"
show_x(binding) #=> prints "undefined local variable or method `x' for main:Object"
end
def ex2
x = 123
y #+> prints "x = 123"
show_x(binding) #+> prints "x = 123"
end
ex1
ex2
要解决这个问题,你需要做一些错误的评估字符串内处理:
require 'caller_binding'
def show_x(b)
begin
eval <<-SCRIPT, b
if defined? x
puts "x = \#{x}"
else
puts "x not defined"
end
SCRIPT
rescue => e
puts e
end
end
def y
show_x(caller_binding)
end
def ex1
y #=> prints "x not defined"
show_x(binding) #=> prints "x not defined"
end
def ex2
x = 123
y #+> prints "x = 123"
show_x(binding) #+> prints "x = 123"
end
ex1
ex2
我试过了在我的盒子和喜欢我的答案,它依靠x也在不同的范围内声明(这里如果x = 456没有说明,它不起作用)。 – 2009-08-22 18:18:41
如果x在调用者的绑定中没有定义,它不会找到它,只不过是'eval“放x”,binding()'可以在调用者的上下文中工作。看到我的编辑更多。 – rampion 2009-08-23 09:17:53
@Chris:Rampion的'caller_binding'实现没有特别的适应性。尽管为了与Ruby 1.8.7一起工作,它需要将“1.8.7”=> -3'添加到它的偏移散列中。 – Chuck 2009-08-23 09:26:08