Ruby tool to browse through installed gems code

2019-07-27 11:44发布

问题:

I am using a gem and I have trouble figuring out how to use a specific method.

Currently to understand how it works, I have to go to github, search the gem realise the code is from a dependency, search the code repo for the other gem, realise it's another gem, locate it, find the class, and from there go from one class to another with a lot of browsers tabs open.

I am on Linux using sublime text. Is there some tool that would allow me to directly access the code from a gem ?

回答1:

You could use pry with source-browsing.

It's a console similar to IRB, and you can view the definition of any class/method that is written in plain Ruby.

Here's an example with rgeo gem :

> pry                                                                                                               
[1] pry(main)> require 'rgeo'
=> true
[2] pry(main)> show-source RGeo::Cartesian.factory

From: ~/.rvm/gems/ruby-2.3.1/gems/rgeo-0.6.0/lib/rgeo/cartesian/interface.rb @ line 27:
Owner: #<Class:RGeo::Cartesian>
Visibility: public
Number of lines: 7

def preferred_factory(opts_ = {})
  if ::RGeo::Geos.supported?
    ::RGeo::Geos.factory(opts_)
  else
    simple_factory(opts_)
  end
end


回答2:

You could "vendorize" your gems, that is instead having them installed somewhere else on your system they are within your project. That way your editor has access the the source code more easily.

If you are using bundler you can do something like bundle package which will put your gems in ./vendor/cache. Reference: How do I vendorize gems for Rails3/Bundler

Another way, which I use, is gem_home this will manage your $GEM_HOME, which is where gems are installed. You would do something like:

cd ~/dev/my_project
gem_home .
bundle install

You will then find all your gems in ~/dev/my_project/.gems.

Which ever method you use don't forget to exclude the directory from version control, e.g. add to .gitignore.



标签: ruby rubygems