Cedric H.
Cedric H.

Reputation: 8298

Ruby require path

I have a Ruby code with different classes in a few files. In one file, I start the execution. This file requires my other files.

Upvotes: 11

Views: 29195

Answers (3)

Alex V
Alex V

Reputation: 18306

If you're using Ruby 1.9 or greater, user require_relative for your dependencies.

require_relative 'foo_class'
require_relative 'bar_module'

Upvotes: 19

Piccolo
Piccolo

Reputation: 1666

I know this is an old question, but there is an updated answer to it, and I wanted to post it:

Starting in a more recent version of Ruby (I'm not sure when), you can require files in the same directory by using the following:

require './foo_class'
require './bar_module'

and it'll load files called foo_class.rb and bar_module.rb in the same directory.

For checking if your file is being required or ran normally, check the other answer.

Upvotes: 7

Dale Campbell
Dale Campbell

Reputation: 496

If you want to check if a Ruby file is being 'require'ed or executed with 'ruby MyRubyCode.rb', check the __FILE__ constant.

# If the first argument to `ruby` is this file.
if $0 == __FILE__
  # Execute some stuff.
end

As far as the require/$LOAD_PATH issue, you could always use the relative path in the require statement. For example:

# MyRubyCode.rb
require "#{File.dirname(__FILE__)}/foo_class"
require "#{File.dirname(__FILE__)}/bar_module"

Which would include the foo_class.rb and bar_module.rb files in the same directory as MyRubyCode.rb.

Upvotes: 16

Related Questions