DEV Community

Augusts Bautra
Augusts Bautra

Posted on

TIL: Ruby's TracePoint

Today I was looking into some cryptic warnings we're getting on CI, and querying GPT about possible ways to understand where they're being emitted from I was pointed to TracePoint class.

It's an extremely powerful API that allows instrumenting many key Ruby program events such as raises, method calls, block entries etc. (see docs for the full list) without polluting (or knowing, hehe) the defining code.

For example, we know an offending instance method name example_method, but naught else. We can instrument all method calls and look for a match

def example_method
  "yay"
end 

TracePoint.new(:call) do |tp|
  puts [tp.lineno, tp.defined_class, tp.method_id, tp.event].to_s if tp.method_id == :example_method
end.enable do
  example_method
end
# [1, Object, :example_method, :call]
#=> "yay"
Enter fullscreen mode Exit fullscreen mode

I imagine you could (ab)use this for some fancy framework meta- programming to gracefully achieve reactions to macro calls etc.

Top comments (0)