Auto-Load Applications within Pry & IRB

Adler @ 2016-10-02

Rails console is convenient that we enter the console with the Rails application fully loaded. We do not need to load any class or library before using it. However, it would be great if we do the same in any other Ruby application, especially when we're developing a Ruby gem.

It is possible with Ruby built-in mechanism .irbrc (or .pryrc if using pry). The .irbrc, like other rc files, load the scripts before entering the console. In this case, we can setup an entry point where all dependencies are required in the development.

Let's say we have a library called foobar and the file structure looks like:

- lib
  - foobar
    - version.rb
    - foo.rb
    - bar.rb
  - foobar.rb
- Gemfile

This typical gem library structure generates a Foobar constant at the top level. However, if we simply run:


there will be no Foobar constant available for us before we require it within the irb:

# => NameError: uninitialized constant Foobar
require_relative "lib/foobar"
# => true
# => Foobar

It works, but it would be annoying if we have to do this every time we enter the console. What we want to achieve is when we run irb and the whole library in lib directory is loaded.

.irbrc (or .pryrc)

This is where .irbrc comes in. This could be simple if we add .irbrc in the root directory and add the following content.

require_relative "lib/foobar"

and viola!



# => Foobar

This could be even more useful if we want to add more commands in the .irbrc.

Pry Editor

There are more options for customization in .pryrc. For example, we can change the default editor in .pryrc like:

Pry.editor = "vim"

so when we enter edit command in the console, vim editor will show up.