2008-09-20 64 views
7

下面是一个典型的Ruby on Rails的回溯过去的几帧: application trace http://img444.imageshack.us/img444/8990/rails-lastfew.png如何在ruby回溯中获取源和变量值?

这里是Python中的典型Nevow追溯的最后几帧: alt text http://img444.imageshack.us/img444/9173/nw-lastfew.png

这不仅仅是网络环境或者,你可以在ipython和irb之间进行类似的比较。我怎样才能在Ruby中获得更多这样的细节?

+0

嘿,图像链接已损坏。 – alanjds 2017-11-01 16:17:26

回答

7

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应能正常工作,但也许慢)

更新

好吧,我想通了。 Longish代码如下:

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