This post was extracted and adapted fromThe Rails and Hotwire Codex.
Rails 7 includes theofficial Ruby debugger. It also usesForeman to orchestrate multiple processes in development. This way you can run the Rails server along with processes to watch and compile your frontend assets using a single command.
Annoyingly, this makes debugging trickier. You can't just add a breakpoint in your app and run commands in the console. The same Terminal window is running multiple processes, so won't always be interactive.
Thedebug
gem supports remote debugging which is useful in such cases. Using this setup, an external, independent debugger process attaches to anotherdebuggee Ruby process.
Enable remote debugging in your Rails app by adding the below lines to yourapplication.rb
.
require"rails/all"ifdefined?(Rails::Server)&&Rails.env.development?require"debug/open_nonstop"end# ...
We verify the Rails environment is development and that theRails::Server
constant is defined before enabling remote debugging. The latter check ensures remote debugging is enabled only when the app runs in the context of a web server. It shouldn't be enabled in other contexts like the Rails console or a background job processor like Sidekiq.
Now when you start the Rails server in development, thedebug
gem will open aUNIX domain socket which the debugger process can connect to.
Start the server usingbin/dev
and in another Terminal window, run:
$ bundle exec rdbg -a
If the Rails server is the only debuggable process running (it should be), the debugger will connect. You can add then breakpoints in the app and run commands in the debugger process!
Ctrl+D
will exit the debugger and leave the Rails server running. I recommend doing this after you've finished debugging. Check out the docs for the full list of available commands:https://github.com/ruby/debug#control-flow.
NOTE:You can also use the statementrequire "debug/open"
instead ofrequire "debug/open_nonstop"
. The downside here is the program will be paused on launch until you attach the debugger andcontinue
it. This can get very fiddly given how often the server needs to be restarted during development.
If you liked this post, check out my book,The Rails and Hotwire Codex, to level-up your Rails and Hotwire skills!
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse