
Am I the only programmer who once or twice messed up production by thinking it was development? In this short tutorial, I’ll describe a simple way to reduce the risk of mixing up your current working Rails environment.
How to customize Rails console prompt?
By default, Rails console displays info about the current working environment on startup:
The issue with this setup is that the environment name is pushed off the screen once you run a few commands. If you’re working in multiple terminal tabs, it’s just too easy to confuse environments.
You can easily improve it by adding the following file to your Rails project:
config/initializers/console_prompt.rb
require 'irb'
env = Rails.env
env_color = if env.production?
"\e[31m#{env}\e[0m"
else
env
end
IRB.conf[:PROMPT] ||= {}
IRB.conf[:PROMPT][:RAILS_APP] = {
PROMPT_I: "YourApp (#{env_color}) > ",
PROMPT_N: nil,
PROMPT_S: nil,
PROMPT_C: nil,
RETURN: "=> %s\n"
}
IRB.conf[:PROMPT_MODE] = :RAILS_APP
and enabling it in app configuration:
config/application.rb
console do
ARGV.push "-r", root.join("config/initializers/console_prompt.rb")
end
Now your console prompt will ALWAYS display the current Rails environment. With a bit of ANSI coloring magic, we can highlight the environment name if you’re on production:
Summary
For me, this simple hack highly improves the comfort of working in the Rails console. Before implementing it I’ve manually run Rails.env
before executing any potentially destructive command. I hope that adding it to your project will help you prevent unnecessary mistakes.