如果方法A
被其他方法调用,
有没有办法知道在运行时是哪个函数调用它。
我可以 grep 整个项目来列出所有可能的调用路径,
但如果我能在运行时知道它,它会更有帮助。
如何通过在 method A
例如,调用流程可能
C() -> B() -> A()
H()-> G()-> B()-> A()
我想知道最近的 3 或 5 个方法调用,
我想在 Rails 项目中跟踪我的 Controller 和助手中的流程 但我需要示踪剂,它向我展示了。
Routing Error
undefined method `on' for Tracer:Class
Try running rake routes for more information on available routes.
这是我的代码
Tracer.on
def generate_nonexisted_book(price)
~~~
end
Tracer.off
最佳答案
Ruby 有一个名为 Tracer
的 stdlib .我会用下面的一个小例子来演示它:
require 'tracer'
Tracer.on
def a;end
def b; a ; end
def c; b ; end
c
Tracer.off
现在让我运行代码:
(arup~>test)$ ruby -v c.rb
ruby 2.0.0p0 (2013-02-24 revision 39474) [i686-linux]
#0:c.rb:4::-: def a;end
#0:c.rb:5::-: def b; a ; end
#0:c.rb:6::-: def c; b ; end
#0:c.rb:7::-: c
#0:c.rb:6:Object:>: def c; b ; end
#0:c.rb:6:Object:-: def c; b ; end
#0:c.rb:5:Object:>: def b; a ; end
#0:c.rb:5:Object:-: def b; a ; end
#0:c.rb:4:Object:>: def a;end
#0:c.rb:4:Object:<: def a;end
#0:c.rb:5:Object:<: def b; a ; end
#0:c.rb:6:Object:<: def c; b ; end
#0:c.rb:8::-: Tracer.off
(arup~>test)$
这里的一些符号符号的描述出现在输出中:
- +>+ - 调用 Ruby 方法
- - - 在新行上执行代码
- +<+ - 从 Ruby 方法返回
关于ruby-on-rails - 如何获取/追溯方法调用堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21948812/