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

后端 未结 11 1852
臣服心动
臣服心动 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条回答
  •  Happy的楠姐
    2020-11-27 09:39

    $LOAD_PATH << '.'
    
    $LOAD_PATH << File.dirname(__FILE__)
    

    It's not a good security habit: why should you expose your whole directory?

    require './path/to/file'
    

    This doesn't work if RUBY_VERSION < 1.9.2

    use weird constructions such as

    require File.join(File.dirname(__FILE__), 'path/to/file')
    

    Even weirder construction:

    require File.join(File.expand_path(File.dirname(__FILE__)), 'path/to/file')
    

    Use backports gem - it's kind of heavy, it requires rubygems infrastructure and includes tons of other workarounds, while I just want require to work with relative files.

    You have already answered why these are not the best options.

    check if RUBY_VERSION < 1.9.2, then define require_relative as require, use require_relative everywhere where it's needed afterwards

    check if require_relative already exists, if it does, try to proceed as in previous case

    This may work, but there's safer and quicker way: to deal with the LoadError exception:

    begin
      # require statements for 1.9.2 and above, such as:
      require "./path/to/file"
      # or
      require_local "path/to/file"
    rescue LoadError
      # require statements other versions:
      require "path/to/file"
    end
    

提交回复
热议问题