【问题标题】:Display the backtrace of a method call from the repl?显示来自 repl 的方法调用的回溯?
【发布时间】:2015-02-16 17:57:27
【问题描述】:

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

类似

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

【问题讨论】:

    标签: ruby pry


    【解决方案1】:

    您可以使用TracePoint 类。

    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 的发布。早些时候,有一个类似的工具可以让您跟踪任何 Ruby 程序中的操作,称为set_trace_func。但是,使用它真的很慢而且很难看。这个新的TracePoint API 旨在取代它。

    【讨论】:

      猜你喜欢
      • 2016-02-02
      • 1970-01-01
      • 1970-01-01
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多