【问题标题】:Ruby TracePoint: How to trap definition of a specific class?Ruby TracePoint:如何捕获特定类的定义?
【发布时间】:2017-07-25 06:37:37
【问题描述】:

我正在尝试了解如何使用 Ruby 的 TracePoint API 来捕获特定类(例如“Resolv”)的定义和后续重新定义。我可以使用以下方法捕获 所有 类定义:

TracePoint.trace(:class) do |tp|
  require 'pry'; binding.pry # for example
end

但是,我无法使用:class:end 参数对其进行过滤,因此我只能捕获Resolv 类。 TracePoint 对象有一个defined_class 属性,但它包含在类定义时谁是自我(即nil,又名(main)),而不是即将处理其定义的类。我也找不到查看正在处理的文件和行的方法。 一个binding 变量,但它不包含任何变量。

我该怎么做?

【问题讨论】:

  • tp.linenotp.path 不给你线路和文件吗?
  • 是的,你是对的。我不知道我是怎么错过的。谢谢。

标签: ruby class tracepoint


【解决方案1】:

我知道的唯一方法是跟踪 所有 类定义并使用 TracePoint#self 过滤它们:

TracePoint.new(:end) do |tp|
  if tp.self == Resolv
    # yay, we are in
    # tp.disable # use this to unset a trace point
  end
end.enable

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-30
    • 2013-04-07
    • 2018-06-28
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多