automatically load project's environment to irb
Asked Answered
S

4

16

Rails has useful command rails console, which downloads all necessary data and then we can interact with rails project in irb. Is there the same technique for Ruby project (built on Ruby language)? By this trick I can play with Ruby project in the irb without concerning about loading libraries, modules, classes, files and so on. Thanks

Sprig answered 24/3, 2011 at 20:8 Comment(0)
C
22

Your project should have one file which loads the environment. Assuming your project is in lib/project.rb then simply:

$ irb -Ilib -rproject
Cithara answered 25/3, 2011 at 0:20 Comment(0)
V
1

From one of my projects:

# Creates an IRB console useful for debugging experiments
# Loads up the environment for the condition passed
def console
  File.open("./tmp/irb-setup.rb", 'w') do |f|
    f.puts "# Initializes the environment for IRb."
    f.puts "Code to initialize your project here"
    f.puts "$: << '#{File.expand_path(".")}/'"  #handle load path       
  end
  irb = RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? 'irb.bat' : 'irb'
  # require your code
  libs =  " -r irb/completion"
  libs <<  " -r #{File.dirname(__FILE__) + "/base"}"
  libs << " -r ./tmp/irb-setup.rb" # require the config file you just wrote
  puts "Loading #{@options.env} environment..."
  exec "#{irb} #{libs} --simple-prompt"
end

The trick is that you construct the irb command to autorequire all the code you need. I also needed to set up some configuration so I add the magick of writing a file I then require in IRb.

Vulcanism answered 24/3, 2011 at 20:17 Comment(2)
Please explain where to put this function in the project and how to call it.Sprig
That kind of depends on how your project is organized. I have it a file that contains a commandline utility that does things like generators, servers, running the code etc. But if you put in a file console.rb and at the end simply add console then it should work when you run it with ruby console.rb it should work. You'll have to customize it to suite your needs, I've tried to indicate where.Vulcanism
S
0

In my case my initialization script was in the current working directory. The below worked for me.

irb -r ./setup.rb
Schonfeld answered 11/12, 2013 at 18:23 Comment(0)
E
0

For any project, you could also add a .irbrc, and require what you want in there, most likely the entry point of the project.

require "lib/project"
Essonite answered 9/11, 2023 at 0:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.