Search code examples
rubyclasstracepoint

Ruby TracePoint: How to trap definition of a specific class?


I am trying to find out how to use Ruby's TracePoint API to trap the definition and subsequent redefinitions of a specific class (e.g. 'Resolv'). I am able to trap all class definitions using:

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

However, I am unable to filter it using either :class or :end parameters so that I could trap only the Resolv class. The TracePoint object has a defined_class attribute, but that contains who is self at the time of the class definition (which was nil, aka (main)), and not the class whose definition is about to be processed. Nor could I find a way to see which file and line were being processed. There is a binding variable, but it contained no variables.

How can I do this?


Solution

  • The only way I am aware of would be to trace all class definitions and filter them with 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