ruby-on-railsruby-on-rails-7irbrails-console

Configuring the console via IRB


I have some code that I would like to automatically execute on a per-project basis when I start up rails c. In one of my Rails 6 projects, I just created a .irbrc file at the top-level of the project, and it successfully executes as expected.

However, for a new Rails 7 (API-only) project that I am working on, the .irbrc file is ignored. I am using rvm, which wants to set the IRBRC environment variable to another file. However, even this config file isn't executed. I've tried both unset IRBRC and export IRBRC=.irbrc, but neither of these by themselves solves the issue.

I finally added gem "irb" to my GEMFILE, ran bundle install. I then ran IRBC=.irbc rails c and then within the console session I invoked IRB.start and it finally loaded the script!

How can I get Rails 7 to properly load my project specific .irbrc file when using the console (only)?


Solution

  • Found a solution here: https://stackoverflow.com/a/57526113/8005367

    Apparently you can now add an initializer file (ex: /config/initializers/console.rb) to configure the console when it runs:

    Rails.application.console do
      puts "Initializing the Rails console..."
      # console configuration here!
    end
    

    I've tested and confirmed that this properly executes only when running the console