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 definerequire_relative
asrequire
, userequire_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
- alas they don't seem to work in Ruby 1.9 throughly, because, for example:require File.join(File.dirname(__FILE__), 'path/to/file')
$ 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:
seems to work, but it's weird and not quite good looking.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.
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.
require
andrequire_relative
? – Colonel Panica.rb
and wanted to make interpreter read and parse contents of fileb.rb
in current directory (usually the same dir as witha.rb
), you'd just writerequire 'b'
and it would be fine as default search path included current directory. In more modern Ruby 1.9, you'll have to writerequire_relative 'b'
in this case, asrequire 'b'
would only search in standard library paths. That's the thing that kind of breaks forward and backward compatibility for simpler scripts that aren't going to be installed properly (for example, install scripts themselves). – GreyCatbackports
just forrequire_relative
, see my answer... – Marc-André Lafortune