Customizing Pry and IRB Sessions
The .irbrc file
The .irbrc
file is usually placed in your home directory (~/.irbc
). This
file is just a regular ruby file and you can write any arbitrary ruby code that
you want to be executed before the IRB session is loaded.
The .pryrc file
The .pryrc
file is very similar to the .irbrc
file and is placed in your
home directory (~/.pryrc
) and this file is loaded before the Pry session is
started.
Customizing the session
If you use a particular gem every time you are in an IRB or a Pry session, you
can simply include that in your .irbrc
or .pryrc
file so you do not have to
manually require that gem every time you enter the session. An example for this
would be the pretty print (pp) library. Just add the require statement in the
rc file and that will load this library whenever you enter the session.
1
|
|
Note: The following customizations are IRB specific and Pry has most of them in-built.
If you use IRB instead of Pry, you will have to install some additional gems to
get the coloring enabled in the output. Pry has this in-built so you do not
have to do any additional work. To enable coloring in IRB, the wirble
gem
should be installed. The following simple configuration will enable coloring
using the wirble
gem.
1 2 3 4 5 6 7 |
|
Tab completion in IRB can be enabled by
1
|
|
Automatic indentation can be set by
1
|
|
If you would like to save the history between IRB sessions, it can be achieved by
1 2 3 4 5 6 |
|
Per-project customization
The .[irb|pry]rc
file can be customized to automatically load the environment
for your project based on your current working directory.
Whenever I work with Ruby projects, I keep a separate window open for my pry
session. I do not want to load and initialize the project every time I enter te
session. I usually have the credentials saved separately in a YAML file. So in
the .pryrc
file, I get the current working directory and based on the
directory, I load and initialize my project. The object I initialize in the rc
file will be available inside the irb/pry session, which I can then use for my
interactions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|
Now that I have my rc file setup to prepare my project when I am in my jenkins_api_client project directory, when I enter the Pry session, my project is loaded and ready for me to play with. If I change my directory to a different project and enter irb/pry session again, that project will be loaded instead.
1 2 3 4 |
|
It is as simple as adding another condition to match your project and name do the initializations to load your project. The above method will work even if you are deep inside your project directory structure as the regex we use to match th current directory uses non-greedy approach.