borjagvo
borjagvo

Reputation: 2071

Navigating through source code efficiently in Ruby

I was trying to find the method being called when Item.where(dst: "video") is called (Item being a Mongoid model). Looking up in the source code, I see that criteria.rb is the place to go to. However, def where calls super. Then Origin::Selectable (included inside Origin::Queryable) defines it:

def where(criterion = nil)
   criterion.is_a?(String) ? js_query(criterion) : expr_query(criterion)
end

Now, I would have to see where js_query and expr_query are, see what they do and so on.

It gets tough going through all this source code and modules, finding all the methods and then trying to figure out how it works.

Is there a better way to do this process to find out how things work?

Upvotes: 1

Views: 83

Answers (2)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

You probably need to improve your editor experience. There are three remarkable abilities (besides many others like Eclipse/Aptana, NetBeans, etc):

Depending on your choice you yield an ability to quickly navigate through your code with either Ctrl+Click or with your preferred keyboard shortcut.

Here on SO this question was asked an amount of times as well: https://stackoverflow.com/search?q=best+ruby+editor

Hope it helps.

Upvotes: 3

sawa
sawa

Reputation: 168071

If you know the class of the receiver (say A) and the method name (say foo), then you can do:

A.instance_method(:foo).source_location

That will give the file name and the line number in most cases. If it returns nil, then it is likely a C-defined method, which does not rely on other Ruby methods.

Another way is to use the pry gem or the method_source gem.

Upvotes: 1

Related Questions