In this post I will cover a few ways to debug code inside Ruby gems in your application.
There are two main debugging styles in Ruby:
Puts Debugging consists in adding
putsstatements in the target code, execute the script or application, and use the output to understand what's going on.
Interactive Debugging enables pausing the program at a specific instruction, examining the current state in a REPL, and doing step-by-step execution.
To debug a library using puts debugging, you'll need to do things differently.
You can run
bundle open to open a gem in your favorite text editor.
EDITORenvironment variable will be used to infer the preferred text editor. I like using Sublime Text or Visual Studio Code to navigate the file tree.
For example, running
bundle open actionview will open the version of the
actionview gem specified in the nearest
In contrast with compiled languages—where libraries are distributed as binaries—in Ruby most libraries are distributed as plain
.rb files which are human-readable.
And human-writable! You can modify the code in a library, restart your app, and your changes will be picked up! 🤩
This is extremely useful when tracking down bugs—you can add
puts or breakpoints as needed, or even modify the behavior of the library.
gem pristine :library:once you are done to undo any changes. Otherwise, you risk relying on behavior that is local and unversioned 🙀
When you need to make extensive changes a nicer flow is to clone the library, and then point to your local copy.
# Assuming rails was cloned in the same parent directory gem 'actionview', path: '../rails/actionview'
If a dependency is specified using a Git repository, prefer local paths in Bundler.
Just as in the previous section, it's important to restart the program you intend to debug after making changes.
Most Ruby programs use
require to load a library into memory, and will use that cached version during their entire running time.
Restarting the program, such as a script or a web development server, ensures that any changes you have made to the library are loaded!
Please refer to the following documentation for more information: