Ruby: require vs require_relative - best practice to workaround running in both Ruby <1>=1.9.2

后端 未结 11 1845
臣服心动
臣服心动 2020-11-27 08:50

What is the best practice if I want to require a relative file in Ruby and I want it to work in both 1.8.x and >=1.9.2?

I see a few options:

11条回答
  •  时光取名叫无心
    2020-11-27 09:45

    One issue I've not seen pointed out with the solutions based on __FILE__ is that they break with regards to symlinks. For example say I have:

    ~/Projects/MyProject/foo.rb
    ~/Projects/MyProject/lib/someinclude.rb
    

    The main script, the entry point, the application is foo.rb. This file is linked to ~/Scripts/foo which is in my $PATH. This require statement is broken when I execute 'foo':

    require File.join(File.dirname(__FILE__), "lib/someinclude")
    

    Because __FILE__ is ~/Scripts/foo so the require statement above looks for ~/Scripts/foo/lib/someinclude.rb which obviously doesn't exist. The solution is simple. If __FILE__ is a symbolic link it needs to be dereferenced. Pathname#realpath will help us with this situation:

    require "pathname"
    require File.join(File.dirname(Pathname.new(__FILE__).realpath), "lib/someinclude")
    

提交回复
热议问题