This module provides relative requires to the requiring file. This
should solve
most of the uglyness of pushing to $LOAD_PATH and loading #expand_path-ed files.
Ideally, that would be something I’d like to see in ruby 2.0
gem install relative-require or source at
Tested with ruby-1.8.7 and ruby-1.9.2
Example project
This example shows that you don’t have to mess with $LOAD_PATH anymore.
Good point. To tell you the truth, it’s something that didn’t exist in
the 1.8 serie and I didn’t really follow the 1.9 development. This is
something that always annoyed me so I decided to tackle the problem.
Still, I believe that there is no need for require_relative (or I didn’t
study the problem enough). By using the “./” notation in your require
path, you basically announce that it will be relative. The current
behavior is to be relative to the pwd, but most of the time (in tests
or in libraries) the most useful is to be relative to the calling’s file
path. In the rare cases where you want to load something from the pwd,
you can fallback to File.join(Dir.pwd, “some-file”).
You don’t need require_relative because you’re doing the same thing as
that
does, and vice versa. No need for you library because we already have a
standard method to do it.
Requires a library whose path is relative to the file containing the
call. Thus, if the directory 1.9 /usr/local/mylib/bin contains the file
myprog.rb and that program contains the following line:
require_relative “…/lib/mylib”
then Ruby will look for mylib in /usr/local/mylib/lib. require_relative
cannot be called interactively in irb.
Thanks James. Is there online documentation for Ruby that’s complete? I
know, for a fact, that there’s a bunch of experienced Ruby developers
who’ve never heard of this particular method. And of course, I’m curious
what else is in those extensions.
Cheers,
Bob
Requires a library whose path is relative to the file containing the call. Thus,
if the directory 1.9 /usr/local/mylib/bin contains the file myprog.rb and that
program contains the following line:
require_relative “…/lib/mylib”
then Ruby will look for mylib in /usr/local/mylib/lib. require_relative cannot
be called interactively in irb.
Sorry for not doing my homework first, I think I will unpublish this
gem. Maybe a backward-compatible require_relative will be more useful.
Just to finish this thread, James and Urabe, do you remember why the
meaning of “./” wasn’t simply changed in #require instead of creating a
new method ?
Thanks James. Is there online documentation for Ruby that’s complete? I know,
for a fact, that there’s a bunch of experienced Ruby developers who’ve never heard
of this particular method. And of course, I’m curious what else is in those
extensions.
I don’t know of a complete online source, no. I still recommend keeping
a copy of the Pickaxe handy for at least that reason.