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

GreyCat picture GreyCat · Dec 2, 2010 · Viewed 72.7k times · Source

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:

  • just do $LOAD_PATH << '.' and forget everything
  • do $LOAD_PATH << File.dirname(__FILE__)
  • require './path/to/file'
  • 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
  • use weird constructions such as
    require File.join(File.dirname(__FILE__), 'path/to/file')
    - alas they don't seem to work in Ruby 1.9 throughly, because, for example:
    $ cat caller.rb
    require File.join(File.dirname(__FILE__), 'path/to/file')
    $ cat path/to/file.rb
    puts 'Some testing'
    $ ruby caller
    Some testing
    $ pwd
    /tmp
    $ ruby /tmp/caller
    Some testing
    $ ruby tmp/caller
    tmp/caller.rb:1:in 'require': no such file to load -- tmp/path/to/file (LoadError)
        from tmp/caller.rb:1:in '<main>'
  • Even weirder construction:
    require File.join(File.expand_path(File.dirname(__FILE__)), 'path/to/file')
    seems to work, but it's weird and not quite good looking.
  • 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.

There's a closely related question at StackOverflow that gives some more examples, but it doesn't give a clear answer - which is a best practice.

Is there are any decent, accepted-by-everyone universal solution to make my application run on both Ruby <1.9.2 and >=1.9.2?

UPDATE

Clarification: I don't want just answers like "you can do X" - in fact, I've already mentioned most of choices in question. I want rationale, i.e. why it is a best practice, what are its pros and cons and why it should be chosen among the others.

Answer

Travis Reeder picture Travis Reeder · Jan 17, 2011

A workaround for this was just added to the 'aws' gem so thought I'd share as it was inspired by this post.

https://github.com/appoxy/aws/blob/master/lib/awsbase/require_relative.rb

unless Kernel.respond_to?(:require_relative)
  module Kernel
    def require_relative(path)
      require File.join(File.dirname(caller[0]), path.to_str)
    end
  end
end

This allows you to use require_relative as you would in ruby 1.9.2 in ruby 1.8 and 1.9.1.