A better Pry prompt for the Rails console

, 2 min read

Update = This is now part of pry-rails.

On any given day I find myself with at least 2 rails consoles open at the same time. One for local development and one for the testing or production environment. All share the same prompt.

In development:

[1] pry(main)> User.destroy_all

In production:

[2] pry(main)> DataCollector.collect

It would be really good to know what environment each rails console is operating on. While it is printed on the start of the rails console session, it usually quickly scrolls off the screen.

What if we accidentally removed the users on the wrong system? Sure, everyone has working backups, database replication and is also testing them regulary, right?

Even if we have working backups, we can still work on preventing accidents. Luckily we have complete control over the pry prompt through the .pryrc configuration file.

The solution

A closer look at the documentation shows that we can easily make text bold and colored in the prompt:

Pry::Helpers::Text.red('I am red.')
Pry::Helpers::Text.bold('I am bold.')

We get the project name using:

File.basename(Rails.root)

The pry prompt can be overridden in the .pryrc with a custom proc:

Pry.config.prompt = proc { |obj, nest_level, pry| 'NicerPrompt'}

Using the above, this is what I am using for all my personal and work projects:

def formatted_env
  case Rails.env
  when 'production'
    bold_upcased_env = Pry::Helpers::Text.bold(Rails.env.upcase)
    Pry::Helpers::Text.red(bold_upcased_env)
  when 'staging'
    Pry::Helpers::Text.yellow(Rails.env)
  when 'development'
    Pry::Helpers::Text.green(Rails.env)
  else
    Rails.env
  end
end

def app_name
  File.basename(Rails.root)
end

if defined?(Rails)
  Pry.config.prompt = proc { |obj, nest_level, _| "[#{app_name}][#{formatted_env}] #{obj}:#{nest_level}> " }
end

Here is what it looks like:

selection_220 selection_218 selection_219


avatar

Philipp Hansch

Full Stack Developer

Philipp is a full stack developer currently heavily involved with Rust. Most notably he's a member of the Clippy team where he helps with bugfixing and documentation. You can follow him on Twitter and find him on GitHub as well as Patreon.