Forum: Ruby on Rails Requiring /lib files in a cross-platform way.

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
B780ee0ee1480454a85df58536702f63?d=identicon&s=25 Alder Green (Guest)
on 2006-06-01 12:38
(Received via mailing list)
Hi.

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?
455ac2a64d06dc8461f4d258d7f7e980?d=identicon&s=25 Michael Trier (Guest)
on 2006-06-01 12:56
(Received via mailing list)
if you have something like:

require_dependency 'foo'

in your environment.rb file it picks it up from lib automatically.

Michael
B780ee0ee1480454a85df58536702f63?d=identicon&s=25 Alder Green (Guest)
on 2006-06-01 20:10
(Received via mailing list)
On 6/1/06, Michael Trier <mtrier@gmail.com> wrote:
> http://lists.rubyonrails.org/mailman/listinfo/rails
>

Indeed.

I looked into the source of the problem:

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.

--
-Alder

[1] http://wiki.rubyonrails.com/rails/pages/RequireDependency
455ac2a64d06dc8461f4d258d7f7e980?d=identicon&s=25 Michael Trier (Guest)
on 2006-06-02 02:35
(Received via mailing list)
Wow, thanks for the investigation.  It's good to know.

Michael
This topic is locked and can not be replied to.