← 피드로
Today I was looking into some cryptic warnings we’re getting on CI. Querying GPT about possible ways to understand where they’re being emitted 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.
추출 본문 · 출처: dev.to · https://dev.to/epigene/til-rubys-tracepoint-397e
답글 남기기