Ruby debugging: How to find a method/variable/callback declaration/defined in ruby/ruby on rails projects

Ruby debugging: How to find a method/variable/callback declaration/defined in ruby/ruby on rails projects

Sometimes when you’re playing with new code it is kind of difficult to find out where they are declared or maybe this method are declared using metaprogramming and they are not explicitly declared:

In most of the cases you can just copy your method or function and search it in the repository using ack http://beyondgrep.com/ or silver searcher(ag) https://github.com/ggreer/the_silver_searcher but if you are not able to find the method you’re looking for using some of this searcher tools you can use some gem for debugging for example debugger https://github.com/cldwalker/debugger or pry https://github.com/pry/pry.

If you’re using pry you can find very useful the command bellow:

Just put a binding.pry in your controller/model/library/class and when the flow is paused then play with the commands

find-method your-method-name

The command above will show you something like:

Spree::OrderContents
Spree::OrderContents#adjust_price

but if I want to see what is the content for that method I will suggest you to use:

show-source adjust_price

And you will see something like:

From: /Users/crowdint/Projects/mysuperduperproject/app/models/spree/order_contents_decorator.rb @ line 2:
Owner: Spree::OrderContents
Visibility: public
Number of lines: 5

def adjust_price(variant, price)
  line_item = order.find_line_item_by_variant(variant)
  line_item.price = price
  line_item.save
end

If the previous commands does not work for you, you can use the ruby method

source_location

Which respond with the file name where the method is defined in my case for instance:

variant.price_for_user.source_location
from /Users/crowdint/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/bundler/gems/spree_user_groups-01c3d21b09be/app/models/spree/variant_decorator.rb:3:in `price_for_user'

and there you go now you’re able to find easily a method declaration in your ruby projects

H.

No Comments

Post A Comment