如何获得红宝石回溯中的源值和变量值?
时间:2020-03-06 14:28:32 来源:igfitidea点击:
这是典型的Ruby on Rails回溯的最后几帧:
应用程序跟踪http://img444.imageshack.us/img444/8990/rails-lastfew.png
以下是Python中典型的Nevow回溯的最后几帧:
替代文字http://img444.imageshack.us/img444/9173/nw-lastfew.png
这不仅是Web环境,还可以在ipython和irb之间进行类似的比较。如何在Ruby中获取更多此类详细信息?
解决方案
AFAIK,一旦捕获到异常,就无法抓住提出异常的上下文。如果捕获异常的新调用,则可以使用evil.rb的Binding.of_caller来获取调用范围,并执行
eval("local_variables.collect { |l| [l, eval(l)] }", Binding.of_caller)
但这是一个很大的漏洞。正确的答案可能是扩展Ruby以允许对调用堆栈进行某种检查。我不确定某些新的Ruby实现是否允许这样做,但是我确实记得对Binding.of_caller的强烈反对,因为这会使优化工作变得更加困难。
(说实话,我不明白这种强烈反对:只要解释器记录了有关执行的优化的足够信息,Binding.of_caller应该可以工作,尽管速度可能很慢。)
好的,我知道了。冗长的代码如下:
class Foo < Exception
attr_reader :call_binding
def initialize
# Find the calling location
expected_file, expected_line = caller(1).first.split(':')[0,2]
expected_line = expected_line.to_i
return_count = 5 # If we see more than 5 returns, stop tracing
# Start tracing until we see our caller.
set_trace_func(proc do |event, file, line, id, binding, kls|
if file == expected_file && line == expected_line
# Found it: Save the binding and stop tracing
@call_binding = binding
set_trace_func(nil)
end
if event == :return
# Seen too many returns, give up. :-(
set_trace_func(nil) if (return_count -= 1) <= 0
end
end)
end
end
class Hello
def a
x = 10
y = 20
raise Foo
end
end
class World
def b
Hello.new.a
end
end
begin World.new.b
rescue Foo => e
b = e.call_binding
puts eval("local_variables.collect {|l| [l, eval(l)]}", b).inspect
end

