开发者

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开发者_Python百科 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜