Coming from languages like Swift and Objective-C, using a proper debugger where I don’t have to edit my code to log something or pause execution is pretty critical for tracking down issues quickly. So — I thought — we’re using puma-dev
to run our Rails app during development, that’s a common setup, and so there must be easy instructions for how to attach Visual Studio Code’s debugger to a running app. Well, not that I could find. I did manage to patch it together through a combination of reading Stack Overflow posts and experimentation.
So, here it is.
Set up debug port environment variable
First, we need to add an environment variable in a place that puma-dev will load from. I put mine in ~/.powconfig
, because that’s the first thing that gets loaded and it’s in my home directory.
Edit ~/.powconfig
to include this:
export RUBY_DEBUG_PORT=1234
Update Gemfile
Make sure you’ve got these under :development
:
gem "ruby-debug-ide"
gem "debase" # or byebug
I’m sure there’s a way to make this work with the new debugger that comes packaged with Ruby 3.1+ (rdbg
), but that’s going to be an exercise for another time.
Add Rails initializer to start rdebug-ide
Create a file in /config/initializers/
called start_debugger.rb
(or whatever you want), and add this code:
if Rails.env.development? && ENV['RUBY_DEBUG_PORT']
require "ruby-debug-ide"
Debugger.start_server nil, ENV['RUBY_DEBUG_PORT'].to_i
end
Add Launch Target to project in Visual Studio Code
Add this configuration to <app root>/.vscode/launch.json
:
{
"configurations": [
{
"name": "Remote Debug",
"type": "Ruby",
"request": "attach",
"remoteHost": "127.0.0.1",
"remotePort": "1234",
"remoteWorkspaceRoot": "${workspaceRoot}",
"cwd": "${workspaceRoot}",
}
]
}
Finally
Restart your app with touch tmp/restart.txt
.
Test it out by running “Remote Debug”, setting a breakpoint in one of your controllers, and refreshing the page that will trigger the code. If everything is setup correctly, your app should pause at the breakpoint.
Congratulations! 🎉
Top comments (1)
I cannot find a vscode extension that enables me to use "type": "Ruby". I can use "type": "rbdg" and "type": "ruby_lsp" but not Ruby. Which extension do I need for that?