Sometimes we can run into bugs in our application that seem to come up out of nowhere. Even after debugging the failing element of our app, it’s just not possible to find the cause of the issue. It is at that moment when we start thinking that maybe the error is not in our code base but somewhere else, maybe in one of those suspicious gems we added recently. But, are we right? Well, there’s a way to find out. It’s time to debug those pesky gems!
Why to debug RubyGems
There should be hundreds of reasons. According to my experience, I can list a few:
- To better understand what’s going on (looking at the context of the code to better understand an error). Try finding conventions inside the gem that may be hiding errors
- To learn from the code (coding style, metaprogramming tricks, etc)
- To see the interactions with other gems
How to open the gem’s code
Once we identify the gem we want to inspect, I can think of two options to open the gem’s code:
- Clone the gem’s repository in your local machine
Checkout the required version e.g.
git checkout tags/v1.0.1
Add the gem to your Gemfile pointing to the code installed locally, e.g.
gem ‘carrierwave’, 1.0.1, path: '~/path/to/the/gem'
Run bundle install
I think this option is better because we can open the gems that are already installed in our local machines.
Using an editor:
- Set EDITOR or BUNDLE_EDITOR env variables. For instance:
export BUNDLER_EDITOR='code'if you use vscode 😉
Open the gem’s code folder with
Opening the gem’s folder:
- Use the command
bundle showto show the gem’s folder path, e.g. in Mac we can use the command:
$ open $(bundle show )
Modifying the gem’s code
Once we have access to the gem’s code, we can modify it or debug it using the tools we usually use, like
After modifying the code, we might need to stop
spring to see the changes. Use
After we made many changes, it might not be easy to revert them because we are not tracking the gem’s code as part of our project. The good news is that we can reinstall a clean version of the gem with:
bundle exec gem pristine
And that’s it. I hope this was useful. Happy bug hunting!🐞