开发者

automatically load project's environment to irb

开发者 https://www.devze.com 2023-02-19 19:35 出处:网络
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

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 i开发者_JS百科n the irb without concerning about loading libraries, modules, classes, files and so on. Thanks


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

$ irb -Ilib -rproject


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.


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

irb -r ./setup.rb
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号