How to customize your Pry prompt to include your application name and Rails environment

Every developer loves to individualize prompts and play around with the cool features. Or at least... I do. Here's how to customize your Pry prompt, if you're using Pry in your rails console.

Then add the following to config/initializers/pry.rb:

if defined?(Pry)
  Pry::Prompt.add(:custom, 'Custom Prompt with app name and environment') do |context, nesting, pry, sep|
    formatter = Pry::Helpers::Text

    app_name = begin
      name = Rails.application.class.module_parent_name
      formatter.blue(name)
    end

    env_name = case Rails.env
      when "development"
        formatter.bright_green("dev")
      when "production"
        formatter.bright_red("prod")
      when "staging"
        formatter.bright_yellow("stag")
      else
        formatter.bright_yellow(Rails.env)
    end

    "#{app_name} #{env_name} #{formatter.purple(Pry.view_clip(context))} #{sep} "
  end

  Pry.config.prompt = Pry::Prompt.all['custom']
end

The result:

Image

Or, for a different variant:

if defined?(Pry)
  Pry::Prompt.add(:custom, 'Custom Prompt with app name and environment') do |context, nesting, pry, sep|
    formatter = Pry::Helpers::Text

    main_color = formatter.method(:purple).curry
    env_color, env_name = case Rails.env
      when "development"
        [formatter.method(:bright_green).curry, "dev"]
      when "production"
        [formatter.method(:bright_red).curry, "prod"]
      when "staging"
        [formatter.method(:bright_yellow).curry, "stag"]
      else
        [formatter.method(:bright_yellow).curry, Rails.env]
    end
    app_name = Rails.application.class.module_parent_name

    "#{main_color[app_name]} #{env_color[env_name]} #{main_color[Pry.view_clip(context)]} #{env_color[sep]} "
  end

  Pry.config.prompt = Pry::Prompt.all['custom']
end

Image

Of course you should customize that to your own liking (colors, separators, ...). Happy tweaking!

Judith Roth