Restarting the Rails server from the Rails console
If you’re like me, you have your Rails environment fully dockerized. You have one terminal window open that is shelled into the container, and probably running the Rails Console. It can be inconvienient to open another terminal window, or drop out of the Console in order to run a command line invocation to restart the Rails server process.
But even if that’s not you, sometimes it’s just useful to be able to restart the Rails server with a boot from the Rails console that you’re in.
Luckily, you can add your own custom commands to the Rails console, and
specifically in this case, Pry. I use Pry (and
pry-rails), and you probably
would like using it too.
Adding custom Console commands to the Rails Console
- Since we don’t autoload
/libanymore, create a
- Create a file in that new
- Inside that file, place the following code:
module RailsConsoleCommands def restart_server! %x(touch tmp/restart.txt) "Restarting Rails Server..." end end
Now, in your
development.rbfile, you’re going to tell the Rails console and Pry to add this new method as a command:
# Add this to the bottom of your development.rb file console do require_relative '../../app/lib/rails_console_commands' TOPLEVEL_BINDING.eval('self').extend RailsConsoleCommands end
- Now, when you run
bin/rails cand type
restart_server!, you will indeed see that the Rails server is restarted. Magic!
This is a minor improvement to my DX, definitely sharpening the saw here, but it honestly saves more than a few seconds every day as I do deep work on my Rails app that the in-built code reloading can’t handle. YMMV.
Obviously there’s no limit to the custom commands you could add. Have fun.