rails
Automatically open the browser when the Rails server starts
Create React App has done this since 2016. Why not Rails?
When I first dipped my toe into the React world back in 2018, an immediate pleasant surprise was running yarn start
and seeing my browser open straight to the spinning React logo. The fact that Create React App launched the localhost URL with the correct port may have only saved me a few seconds of typing and consulting the README, but I appreciated the gesture. Surely I could make Rails – a framework known for developer productivity and surprising “magic” – mimic this behavior?
Let’s write a puma plugin
I wanted Rails to open the browser for me at the end of the boot process, once the puma web server was ready to receive requests. Luckily, puma has a plugin system that lets me do that:
require "puma/plugin"
Puma::Plugin.create do
def start(launcher)
return unless defined?(Rails) && defined?(Launchy)
return unless Rails.env.development?
binding = launcher.options[:binds].grep(/^tcp|ssl/).first
return if binding.nil?
url = binding.sub(/^tcp/, "http").sub(/^ssl/, "https").sub("0.0.0.0", "localhost")
Launchy.open(url)
end
end
Here I define a puma plugin that discovers what port Rails is using and uses the
launchy
gem to open the browser with that URL on startup. Only in development, of course.
Register the plugin
To make puma aware of my custom plugin, I added this to the bottom of my puma config:
# Automatically open the browser when in development
require_relative "../lib/puma/plugin/open"
plugin :open
Require the plugin and register it with puma.
Install launchy
The launchy gem takes care of figuring out what the default browser is on my computer and how to open it.
group :development do
gem "launchy"
end
Add
launchy
and run bundle install
.
Success!
Now, no matter how I start the Rails server – bin/rails s
, bin/dev
, etc. – my browser magically opens a tab to my app.
I’ve included this and other tricks in my rails-template starter project. Check it out if you are creating a new Rails app and are looking to go beyond the Rails defaults.