Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

automatically load project's environment to irb

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

like image 249
megas Avatar asked Mar 24 '11 20:03

megas


People also ask

How do I load a Ruby file in irb?

From the main menu, choose Tools | Load file/selection into IRB/Rails console.

How do I run an irb?

Starting and Stopping IRB You can start it on any computer where Ruby is installed by executing the command irb from your command line interface. The prompt indicates that you're running IRB and that anything you execute will run in the main context, which is the top-level default context of a Ruby program.

How do I get out of irb?

To leave IRB, type the exit command - this will get you back to your command line.

What is Irbrc?

The . irbrc file is nothing else than a Ruby file that gets evaluated whenever we start the console with irb or rails c . We can place it in a home directory ( ~/. irbrc ) or in the project directory (to scope it per project). But only one of these files will take effect, and the global one has precedence.


2 Answers

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

$ irb -Ilib -rproject
like image 100
cldwalker Avatar answered Sep 28 '22 09:09

cldwalker


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.

like image 35
Jakub Hampl Avatar answered Sep 28 '22 09:09

Jakub Hampl