When you have library foo.rb in your Rails project /lib directory, I
notice that on some platforms - e.g. Windows with WEBrick as a server
you can require it by simply:
require ‘lib/foo’
However on other platforms - e.g. Debian with Lighttpd server via
FastCGI - this does not work, and you need to specify RAILS_ROOT
explicitly, like this:
require “#{RAILS_ROOT}/lib/foo”
So what would you consider the canonical way of requiring /lib files
within Rails in a sensible, cross-platform way? Would it be the
second method, or is there in usage some third methods that I’ve
missed?
The cause is that if you start WEBrick from RAILS_ROOT, the working
directory (Dir.pwd) of at least environment.rb (and it seems likely -
the rest of the application as well) would be RAILS_ROOT. So when you
require ‘lib/foo’
Ruby would check for ./lib/foo.rb, because . is always in its
$LOAD_PATH. Now since ‘.’ is RAILS_ROOT, it would find
RAILS_ROOT/lib/foo.rb, which is what we wanted, so everything’s great.
However, if you load your application through FastCGI (I have checked
this for Lighttpd, but suspect Apache would give similar result) your
working directory shall be that of dispatch.fcgi, i.e. /public. Now
‘.’ is /public, and RAILS_ROOT is nowhere in the $LOAD_PATH if you
haven’t explicitly put it there. So trying to require ‘lib/foo’ would
fail, or at any rate won’t find the desired RAILS_ROOT/lib file.
require_dependency solves this, and enables sensible, cross-platform
requirement of attached libraries. It’s nicer than the working
#{RAILS_ROOT} solution, and also has some additional neat features
[1]. Thanks for notifying me about it.