I’ve been using pry for a while and I’ve always been curious about it. So to see how debuggers work, I tried writing the simplest debugger in Ruby. Thanks to the vast number of rubygems out there, it sums upto just 6 lines.
require 'ripl'
class Binding
def take_a_look
Ripl.start :binding => self
end
end
Now if you want to debug some program, just drop the following line and it’ll fire up a REPL when the interpreter reaches that line.
binding.take_a_look
This is done with the help of the binding
method in ruby which returns the current scope, in the form of an object of the Binding class. That one method is what is responsible for the magic. The ripl
gem provides a REPL, that you can pass a binding object to, so that the REPL’s scope is the binding you pass.
If you are curious and want to give this a try, install the gem take-a-look
. I’ve aliased Binding#take_a_look
to Binding#peep
, because I felt take_a_look was too lengthy for a debugging method name.
The source is here - http://github.com/HashNuke/take-a-look