7

Rails Quick Tip - Display Current Environment in Console Prompt

 2 years ago
source link: https://pawelurbanek.com/rails-console-environment
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Displaying Ruby on Rails env in console is represented by a sign Photo by Markus Spiske on Unsplash
Sponsored by ScoutAPM

A leading-edge performance and error monitoring tool for Ruby applications.

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:

Default Ruby on Rails console prompt

Default Rails console prompt

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:

Custom Ruby on Rails development console prompt

Custom Ruby on Rails production console prompt

Abot for Slack custom console prompt

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK