Restarting the Rails server from the Rails console

Why tho?

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

  1. Since we don’t autoload /lib anymore, create a lib folder under app.
  2. Create a file in that new app/lib folder called rails_console_commands.rb.
  3. Inside that file, place the following code:
     module RailsConsoleCommands
       def restart_server!
         %x(touch tmp/restart.txt)
         "Restarting Rails Server..."
  4. Now, in your development.rb file, 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
  5. Now, when you run bin/rails c and 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.

PS. I was able to piece this together from an ancient blog post Brandon Keepers wrote on Adding helper methods to your Rails console and another post about making that work from Pry.