TracePoint in Ruby

Tram Ho

In Ruby, there is a class that can help you keep track of some activities such as method call, class declaration, exception, … And that class is TracePoint. It is quite useful when you want to track and call a particular function, you can see how that function is called, what it returns.

Create a TracePoint

Here is an example that creates a TracePoint to track function calls from a method:

With event :call you can keep track of the times Ruby calls any method. So you can above that we have trace.enable and trace.disable to ensure that our trace will not run all the time every time a certain method calls, but only limited to a certain range. .

Trackable events

The table below lists the events that TracePoint supports (Ruby 2.5.0):

Name of the eventDescription
lineRun the code on a new line
classAt the beginning of defining a Class or Module
endAt the end of defining a Class or Module
callCall a function in Ruby
returnReturned from a function in Ruby
c_callCall a function written in C
c_returnReturns from a function written in C
raiseWhen an exception is fired
b_callStart a block
b_returnEnd a block
thread_beginWhen starting a thread
thread_endAt the end of a thread
fiber_switchwhen switching context

Fiber is a class in Ruby that makes code that can be stopped and resumed.

Available methods

The table below lists the methods that TracePoint supports (Ruby 2.5.0):

Method nameDescription
bindingReturns the binding object created with the event
defined_classReturns the Class or Module on which the method is being called
disableDisable TracePoint
enableActivate TracePoint
enabled?Check the running status of TracePoint
eventName of the event that is happening
inspectReturns a string containing the TracePoint state
linenoNumber of lines in which the event occurred
method_idThe method name is called
pathThe path of the file is running
raised_exceptionThe value returned from the exception of the event :raise
return_valueReturns values ​​from events :return :c_return :b_return :c_return :b_return
selfReturns the object that created the event

Draw flow to call the function with TracePoint

I wrote a gem to model a function in ruby, with the example at the beginning of this article we will have:

An example of a Fibonacci numbering function:

Code:

Conclude

Hope this article can help you understand more about TracePoint in Ruby.

Gem I wrote

https://github.com/muoihai-com/visual_call_html

Share the news now

Source : Viblo