Search code examples
rubyirb

How to create custom IRB file to load a Ruby project's files, gems and dependencies?


Does anyone know how to run a ruby file from terminal that will require N number of files / gems and finish with an IRB session with those files having already been loaded into memory?

In other words I am hoping for something like this:

$ ruby project_console.rb

# project_console.rb
IRB.new do |config|
  require 'bundler/setup'
  require 'import_project_file'
  require_relative "spec/muffin_blog/app/models/random_file"
  Post.establish_connection({database: "spec/muffin_blog/db/development.sqlite3"})
end

# yay. I'm in my custom IRB session with all of the above already loaded
2.4.1 :001 >

vs

 $ irb
     2.4.1 :001 > require 'bundler/setup'
     => true
    2.4.1 :002 > require 'import_project_file'
     => true
    2.4.1 :003 > require_relative "spec/muffin_blog/app/models/random_file"
     => true
    2.4.1 :004 > Post.establish_connection({database: "spec/muffin_blog/db/development.sqlite3"})
        # this makes me sad because its manual every time I want to play around with my project.

I am developing a ruby project and in the process of building out this project I am finding that I need something like rails console, which loads the entire project and its bundler dependencies into memory so I do not have to do it manually. I thought it would be great if I built my own super thing 'rails console' for the purposes of debugging / playing around with my ruby while building it.

Also I read somewhere that there's an .irbc I could use, but this sounds like I would be changing IRB globally on my machine - and I do not want that. I want to load specific files, gems and configurations per ruby project.

For what it is worth, I have read these SO posts:

However none them seem to provide an answer to my question above.


Solution

  • Very simple, actually:

    #!/usr/bin/env ruby
    require "bundler/setup"
    # ...
    # everything else you need
    # ...
    require "irb"
    IRB.start
    

    When you start IRB using IRB.start, you will have available everything that's been loaded/initialised before it.