Ruby: require vs require_relative - best practice to workaround running in both Ruby <1.9.2 and >=1.9.2 -
what best practice if want require
relative file in ruby and want work in both 1.8.x , >=1.9.2?
i see few options:
- just
$load_path << '.'
, forget everything - do
$load_path << file.dirname(__file__)
require './path/to/file'
- check if
ruby_version
< 1.9.2, definerequire_relative
require
, userequire_relative
everywhere it's needed afterwards - check if
require_relative
exists, if does, try proceed in previous case - use weird constructions such
- alas don't seem work in ruby 1.9 throughly, because, 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 testing $ pwd /tmp $ ruby /tmp/caller testing $ ruby tmp/caller tmp/caller.rb:1:in 'require': no such file load -- tmp/path/to/file (loaderror) tmp/caller.rb:1:in '<main>'
- even weirder construction:
seems work, it's weird , not quite looking.require file.join(file.expand_path(file.dirname(__file__)), 'path/to/file')
- use backports gem - it's kind of heavy, requires rubygems infrastructure , includes tons of other workarounds, while want
require
work relative files.
there's closely related question @ stackoverflow gives more examples, doesn't give clear answer - best practice.
is there decent, accepted-by-everyone universal solution make application run on both ruby <1.9.2 , >=1.9.2?
update
clarification: don't want answers "you can x" - in fact, i've mentioned of choices in question. want rationale, i.e. why best practice, pros , cons , why should chosen among others.
a workaround added 'aws' gem thought i'd share inspired 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 use require_relative
in ruby 1.9.2 in ruby 1.8 , 1.9.1.
Comments
Post a Comment