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?Ruby looks in all the paths specified in the $LOAD_PATH array.
The require method takes the name of the file to require, as a string, as a single argument. This can either be a path to the file, such as ./lib/some_library. rb or a shortened name, such as some_library. If the argument is a path and complete filename, the require method will look there for the file.
$LOAD_PATH is used for the exact same purpose. In ruby an identifier starting with a $ symbol is a global variable. $LOAD_PATH is an array of absolute paths i.e it stores the exact location of all the dependencies in the project.
If you're using Ruby 1.9 or greater, user require_relative for your dependencies.
require_relative 'foo_class'
require_relative 'bar_module'
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With