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:
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")