How to debug ruby super method?

18 Jun 2020

Sometimes in Ruby, I want to check where is the super method being defined? But how can I do that?

It’s simple by using: method(:method_name).super_method. For example:

Recently I write the InsightlyAPI wrapper using ActiveResource, but meet I issue which need I to find where the :to_json being defined. So I add binding.pry to the point where I need to debug and use above commnet patterns:

method(:to_json).super_method.super_method

[9] pry(#<InsightlyAPI::Resources::Contact>)> method(:to_json)
=> #<Method: InsightlyAPI::Resources::Contact(InsightlyAPI::Resources::Base)#to_json>
[10] pry(#<InsightlyAPI::Resources::Contact>)> method(:to_json).super_method
=> #<Method: ActiveResource::Base#to_json>
[11] pry(#<InsightlyAPI::Resources::Contact>)> method(:to_json).super_method.super_method
=> #<Method: ActiveSupport::ToJsonWithActiveSupportEncoder#to_json>

You see, I just found the :to_json’s super_method’s super_method which is defined in ActiveSupport::ToJsonWithActiveSupportEncoder. It means the InsightlyAPI::Resources::Contact#to_json is using ActiveResource::Base#to_json which is using ActiveSupport::ToJsonWithActiveSupportEncoder#to_json.

It’s pretty cool.

And sometimes another the source_location method is also very useful. For example: method(:as_json).source_location

Back to top