27 Jun

Customizing the Rails console


Hi there,


I started to deploy my latest pet project with MRSK and I realized that I miss the customizations from my Rails console on the server. And I thought it might be useful to share how I customize my Rails console, so here we go.


The default Rails console is built on top of IRB, so to customize it, we need to look at IRBs documentation. The docs say that we can either create a global .irbrc in the home directory of the user, or have a project specific one in the project directory, but the home directory one will have a presedence. In my example, I keep it in the project, so I can copy it with docker to the containers when I deploy.


This .irbrc file is a evaluated as ruby, so to do our customizations, we can use our favorite language. The first line in my config is to disable autocompletion because I dislike it:

IRB.conf[:USE_AUTOCOMPLETE] = false

For my dockerized project, I also disable IRB history, since the containers are short-lived, and the history won’t be kept long and it also prevents the exception on the console exit when it fails to write to the file.

IRB.conf[:SAVE_HISTORY] = false if Rails.env.production?

The next thing I have in my file is a prompt customization. I use the pastel gem to colorize the prompt based on the environment:

require "pastel"
pastel = Pastel.new
prompt = case Rails.env
    when "development"
        pastel.black.on_green.bold.dim Rails.env
    when "production"
        pastel.white.on_red.bold.dim Rails.env
    end
# defining custom prompt
IRB.conf[:PROMPT][:CUSTOM] = {   # name of prompt mode
    :PROMPT_I => "#{prompt}>> ", # simple prompt
    :PROMPT_S => "#{prompt}* ",  # prompt for continuated strings
    :PROMPT_C => "#{prompt}? ",  # prompt for continuated statement
    :RETURN   => " => %s\n"      # format to return value
}
IRB.conf[:PROMPT_MODE] = :CUSTOM

As you can see, I don’t do anything fancy in my prompt, just outputting the Rails environment on a green or red background based on the environment. You can get it fancier by using the following special characters in the prompt:

%N    # command name which is running
%m    # to_s of main object (self)
%M    # inspect of main object (self)
%l    # type of string(", ', /, ]), `]' is inner %w[...]
%NNi  # indent level. NN is digits and means as same as printf("%NNd").
      # It can be omitted
%NNn  # line number.
%%    # %

That’s it for this week.