Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Navigating Ruby source code

My main goal is to be able to understand the library/gem that I am using, fully. I tried reading the source code from start to finish on Github but it was really hard.

I thought a more enjoyable and more gentle stepping stone would just be to read the source code of each library/gem method as I use it.

For example I want to know how the redirect_to method in Ruby on Rails works:

  1. How can I look up the source code for the redirect_to method?
    • I am aware that in pry I can do something like show-method method, but how can I do this for methods in the Rails framework?
  2. Do you have any suggestions on how I can better understand gems and their APIs? Just reading the source code seems really hard, especially for frameworks.

Thank You!

like image 562
super_noobling Avatar asked Jun 02 '16 14:06

super_noobling


1 Answers

The RubyMine IDE meets this need for me. It has these features which greatly lower the barrier to reading gem source:

  • Gems are part of the project tree (in the External Libraries pseudo-directory), so you can navigate and even edit them just as you would your own code.

  • A single key command (command-B on Mac) navigates from an identifier (module/class name, method name, etc.) to its declaration, or brings up a list to choose from if there are multiple declarations. It works for both your code and gem code.

  • Another command (option-command-O on Mac) allows you to enter an identifier name to navigate to as above. It automatically includes library code if what you enter is not found in your code; if what you enter is found in your code, you can hit the keys once more to include gem code anyway.

  • The debugger constantly displays the code you're executing. You can set a breakpoint without editing the code where you want it. You can inspect any stack frame above the one that is actually executing. All these features work equally well with your code and gem code.

In general RubyMine features all work with gem code as well as with project code.

Regarding methods of understanding gems other than reading their source code: Most gems are documented in their READMEs (which I invariably read on Github) and possibly other documentation files in the gem's root or in the doc directory. Some gems (the Rails gems included) have rdoc that is worth reading. However, since it's so convenient to navigate from use of a gem to its code, I usually try that first, and read the rdoc (if there is any) in the code before I read the actual code. RubyMine can also display the rdoc for an identifier where it's used (F1 on a Mac), but I've always found it easier to just go straight to the code.

like image 105
Dave Schweisguth Avatar answered Oct 27 '22 04:10

Dave Schweisguth