Reputation: 8298
I have a Ruby code with different classes in a few files. In one file, I start the execution. This file require
s my other files.
DIR2/MyRubyCode
is a link to the main file DIR1/MyRubyCode.rb
, then my requires will fail. I solved the problem by adding the path DIR1
to $LOAD_PATH
before the require
, but I think there would be much better ways to do it. Do you have any suggestions about that?Upvotes: 11
Views: 29195
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
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 require
d or ran normally, check the other answer.
Upvotes: 7
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