Friday, April 15, 2011

Include files in a command line with Ruby

When running ruby scripts as such

ruby some-script.rb

How would I include a file (e.g. configuration file) in it dynamically?

From stackoverflow
  • Actually, I found it. It's the -r command line entry.

  • You can use:

    require 'some_ruby_file'
    

    in some-script.rb. It will load some_ruby_file.rb.

    Macha : Thanks, but not what I asked. I was looking for a way to do it in the command line i.e. without modifying the scripts.
  • As you have found, the -r option is your friend. It also works with IRB:

    irb -ropen-uri
    

    Will do the same as require 'open-uri'

    FWIW, the most common thing I need to include via the command line is rubygems. And since newer versions of ruby come with gems built in I don't want to edit the file, but include it for testing. Luckily the folks who created gems added a little alias sugar.

    You can do the following:

    ruby -rubygems myscript.rb
    

    Instead of the ugly:

    ruby -rrubygems myscript.rb
    

    OK, so it is one character, but thought it was extra polish to make me happier.

0 comments:

Post a Comment