Inspecting Ruby Gems
Have you ever needed inspecting a gem in your local machine?
You need to figure out how a method works, to check the internal state or just out of curiosity.
Today I am here to share two techniques I have been using.
Suppose we are working in a Ruby project which Gemfile contains the following gem:
gem 'grape'Getting a new copy of the gem
The first technique is to git clone the gem into your machine, change the branch/tag to the same version that is in Gemfile.lock and set the path option in your gem entry on Gemfile:
$ pwd
# /Users/myuser/projectsClone the gem you want to inspect:
$ git clone https://github.com/ruby-grape/grape.gitChange the branch/tag:
$ cd grape
$ git checkout v1.0.1Set the path in the Gemfile:
gem 'grape', path: "~/projects/grape"And run bundle to update the reference:
$ bundleThat is it. You can play with your new copy and do whatever you need now.
Let's invoke a new pry session in the requires method for instance:
# ~/projects/grape/lib/grape/dsl/parameters.rb
def requires(*attrs, &block)
binding.pry
# method implementation..
endAccessing the gem in its own path
The second technique is based on inspecting the gem in the path it is already installed in your machine.
Get the path the gem is installed:
$ bundle show grape
# /Users/myuser/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/grape-1.0.2Navigate into:
$ cd /Users/myuser/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/grape-1.0.2This will point to the version we already have in Gemfile.lock, so you don't need to worry about the version.
Play with it:
# ~/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/grape-1.0.2/lib/grape/dsl/parameters.rb
def requires(*attrs, &block)
binding.pry
# method implementation..
endThe only thing here, is that you need to be cautious, because, the code you change inside this path will be applied to any project using that same version.
If you use any other technique, please, let us know in the comments below.
See you.