Custom Colorized Environment String in Rails Console
Ever opened a Rails console and wondered “wait, which environment am I in again?” Yeah, me too. Especially when you’re switching between development, staging, and production faster than you can say User.destroy_all
.
Here’s a neat trick to add some color to your console prompt so you never have to wonder again.
The Problem
The default Rails console visual feedback stops being useful because staging environments are usually configured as “production” on Heroku and most deployment platforms. So Rails.env.production?
returns true for both staging and production. Fun times!
The Solution
Drop this into config/initializers/console.rb
:
# frozen_string_literal: true
require "rails/commands/console/irb_console"
module IRBConsoleWithDeployEnv
def initialize(app, env)
super(app)
@deploy_env = env
end
def colorized_env
IRB::Color.const_set(:DIM, 2) unless defined?(IRB::Color::DIM)
return super unless @deploy_env
IRB::Color.colorize("live:", [:DIM]) +
case @deploy_env
when "staging"
IRB::Color.colorize("stag", [:YELLOW])
when "production"
IRB::Color.colorize("prod", [:RED])
else
IRB::Color.colorize(@deploy_env, [:BLUE])
end
end
Rails::Console::IRBConsole.prepend self
end
And this into config/application.rb
:
module MyApp
class Application < Rails::Application
# Other configurations...
console do |app|
config.console = Rails::Console::IRBConsole.new(app, ENV["DEPLOY_ENV"])
end
end
end
Now your console prompt will show a nice colorized environment string prefixed by your app name. No more “oops, wrong environment” moments.