loading...

tapping_device - a gem for tacking method calls

st0012 profile image Stan Lo ・1 min read

tapping_device is a gem built on top of Ruby’s TracePoint class that allows you to tap method calls of specified objects. The purpose of this gem is to make debugging Rails applications easier.

For example, you can use it to see who calls methods on your Post records

class PostsController < ApplicationController
  include TappingDevice::Trackable

  def show
    @post = Post.find(params[:id])
    tap_on!(@post) do |payload|
      puts "Method: #{payload[:method_name]} line: #{payload[:filepath]}:#{payload[:line_number]}"
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

And you can see these in log:

Method: name line: /PROJECT_PATH/sample/app/views/posts/show.html.erb:5
Method: user_id line: /PROJECT_PATH/sample/app/views/posts/show.html.erb:10
Method: to_param line: /RUBY_PATH/gems/2.6.0/gems/actionpack-5.2.0/lib/action_dispatch/routing/route_set.rb:236
Enter fullscreen mode Exit fullscreen mode

Or you can track all association calls with tap_assoc!. This is very useful for tracking potential n+1 query calls, here’s a sample from my work project

tap_assoc!(order) do |payload|
  puts "Assoc: #{payload[:method_name]} line: #{payload[:filepath]}:#{payload[:line_number]}"
end
Enter fullscreen mode Exit fullscreen mode
Assoc: payments line: /RUBY_PATH/gems/2.6.0/gems/jsonapi-resources-0.9.10/lib/jsonapi/resource.rb:124
Assoc: line_items line: /MY_PROJECT/app/models/line_item_container_helpers.rb:44
Assoc: effective_line_items line: /MY_PROJECT/app/models/line_item_container_helpers.rb:110
Assoc: amending_orders line: /MY_PROJECT/app/models/order.rb:385
Assoc: amends_order line: /MY_PROJECT/app/models/order.rb:432
Enter fullscreen mode Exit fullscreen mode

Although I've been using similar ways on my work for a while, my use cases might be quite limited. So I'd love to hear any feedback or suggestions on this tool 😄

Discussion

pic
Editor guide