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 «require
» или выполняется с помощью «ruby MyRubyCode.rb
», проверьте константу __FILE__
. .
# If the first argument to `ruby` is this file.
if $0 == __FILE__
# Execute some stuff.
end
Что касается проблемы с require/$LOAD_PATH, вы всегда можете использовать относительный путь в инструкции require. Например:
# MyRubyCode.rb
require "#{File.dirname(__FILE__)}/foo_class"
require "#{File.dirname(__FILE__)}/bar_module"
Что включает файлы foo_class.rb
и bar_module.rb
в том же каталоге, что и MyRubyCode.rb
.