Skip to content

Instantly share code, notes, and snippets.

@sephraim
Last active November 6, 2024 19:16
Show Gist options
  • Save sephraim/db256bb7cdf9d11e9c08e377f5efb9cd to your computer and use it in GitHub Desktop.
Save sephraim/db256bb7cdf9d11e9c08e377f5efb9cd to your computer and use it in GitHub Desktop.
[Requiring and using the 'debug' gem in a Ruby script]

Ruby 'debug' gem

To require and use:

require 'debug/prelude'

# Then to use...
debugger

Simply requiring debug only instead of debug/prelude will invoke the debugger immediately, and cause the following error message:

/usr/local/lib/ruby/2.6.0/aarch64-linux/continuation.so: warning: callcc is obsolete; use Fiber instead
Debug.rb
Emacs support available.

/usr/local/lib/ruby/site_ruby/2.6.0/rubygems/core_ext/kernel_require.rb:164:    if RUBYGEMS_ACTIVATION_MONITOR.respond_to?(:mon_owned?)
(rdb:1) exit
/usr/local/lib/ruby/2.6.0/debug.rb:245:in `synchronize': deadlock; recursive locking (ThreadError)
        from /usr/local/lib/ruby/2.6.0/debug.rb:245:in `check_suspend'
        from /usr/local/lib/ruby/2.6.0/debug.rb:843:in `trace_func'
        from /usr/local/lib/ruby/2.6.0/debug.rb:1109:in `block in <class:DEBUGGER__>'
        from /usr/local/lib/ruby/site_ruby/2.6.0/rubygems/core_ext/kernel_require.rb:167:in `require'
        from bin/process-env:13:in `<main>'

Compared to the others:

  • require "debug" - Stops immediately at program start
  • require "debug/prelude" - Enables both the debugger keyword as well as binding.break
  • require "debug/open" - Only enables debugger keyword
  • require "debug/open_nonstop" - Enables debugger but doesn't stop

debug/prelude is particularly useful when you want the flexibility of using either debugger or binding.break methods. The binding.break method is more Ruby-like and can be useful in situations where you want to pass additional options:

require "debug/prelude"

def some_method
  binding.break(pre: "puts 'Stopping!'")  # can include commands to run when breaking
  binding.break(do: "p local_variables")  # can inspect state
end

To debug on raised exceptions:

require 'debug/prelude'

Exception.install_debug_handler  # This will break on any unhandled exception
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment