Exploring TracePoint in Ruby — Part One — Example Code

What is TracePoint?

“A class that provides the functionality of Kernel#set_trace_func in a nice Object-Oriented API.”

- https://ruby-doc.org/core-2.6.1/TracePoint.html

“Establishes proc as the handler for tracing, or disables tracing if the parameter is nil.”

- https://ruby-doc.org/core-2.6.1/Kernel.html#method-i-set_trace_func

TracePoint Example

trace = TracePoint.new(:raise) do |tp|
p [tp.lineno, tp.event, tp.raised_exception]
end
#=> #<TracePoint:disabled>

trace.enable
#=> false

0 / 0
#=> [5, :raise, #<ZeroDivisionError: divided by 0>]
TracePoint.new(:raise)
trace = TracePoint.new(:raise) do |tp|
p [tp.lineno, tp.event, tp.raised_exception]
end
#=> #<TracePoint:disabled>
trace.enable
#=> false
trace.enable do
# Code to be traced - TracePoint is active in here!
end
# TracePoint is off outside of the block
trace.enable { p tp.lineno }
#=> RuntimeError: access from outside
trace = TracePoint.new(:raise) do |tp|
p [tp.lineno, tp.event, tp.raised_exception]
end
#=> #<TracePoint:disabled>
def initialize(&block)
yield(self)
end
0 / 0
#=> [5, :raise, #<ZeroDivisionError: divided by 0>]

Binding

Objects of class Binding encapsulate the execution context at some particular place in the code and retain this context for future use. The variables, methods, value of self, and possibly an iterator block that can be accessed in this context are all retained. Binding objects can be created usingKernel#binding, and are made available to the callback ofKernel#set_trace_func.

- https://ruby-doc.org/core-2.6.1/Binding.html

Parameters and Local Variables

-> a, *b, c: 1, **d, &fn {}.parameters
=> [[:req, :a], [:rest, :b], [:key, :c], [:keyrest, :d], [:block, :fn]]
def extract_arguments(trace)
param_names = trace.parameters.map(&:last)
param_names.map { |n| [n, trace.binding.eval(n.to_s)] }.to_h
end
def extract_locals(trace)
local_names = trace.binding.local_variables
local_names.map { |n|
[n, trace.binding.local_variable_get(n)]
}.to_h
end

Wrapping Up

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store