Macha
Macha

Reputation: 14654

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?

Upvotes: 6

Views: 3670

Answers (5)

James White
James White

Reputation: 21

 -r <library_name>

This causes Ruby to load the library using require.

It is useful when used in conjunction with -n or -p.

Upvotes: 2

Lesly Revenge
Lesly Revenge

Reputation: 922

Before you call require "somefile.rb" you must navigate to the folder that the file is located or you must provide the full path. In example: require "~/Documents/Somefolder/somefile.rb"

Upvotes: -1

csexton
csexton

Reputation: 24783

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.

Upvotes: 10

klew
klew

Reputation: 14967

You can use:

require 'some_ruby_file'

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

Upvotes: 0

Macha
Macha

Reputation: 14654

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

Upvotes: 3

Related Questions