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.

  • Is this a good way to start a ruby code?
  • When I run the code from a symbolic link, for example 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?
12
задан sawa 8 October 2012 в 10:01
поделиться

1 ответ

Если вы хотите проверить, выполняется ли файл 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.

16
ответ дан 2 December 2019 в 03:48
поделиться
Другие вопросы по тегам:

Похожие вопросы: