显示来自 repl 的方法调用的回溯?

Display the backtrace of a method call from the repl?

是否有这样的工具(也许是 pry 插件?)可以打印给定方法调用的回溯,而无需在源代码中插入任何内容?

类似

repl> show-backtrace Cat.new.sleep(5)
# >... Cat.sleep
# >... Cat#initialize
# >...

你可以用 TracePoint class 来代替它。

trace = TracePoint.new(:call) do |tp|
    p [tp.lineno, tp.defined_class, tp.method_id, tp.event]
end

trace.enable

class Cat
  def initialize
    # code
  end
  def sleep(arg)
    arg
  end
end

Cat.new.sleep(5)

# >> [8, Cat, :initialize, :call]
# >> [11, Cat, :sleep, :call]

阅读可用的Events

:call - 调用一个 Ruby 方法。

Ruby has introduced the TracePoint API 随着 Ruby 2.0 的发布。早些时候,有一个类似的工具可以让您跟踪任何名为 set_trace_func 的 Ruby 程序中的操作。然而,使用它真的很慢而且很丑。这个新的 TracePoint API 旨在取代它。