Load unless requires - what are the ramifications

I very new to Ruby (this is my second week), so excuse the “newbieness”
of my question.

I downloaded a project from RubyForge and I’m playing around with the
scripts. I’m having trouble getting the tests to pass - some pass if
run from the main directory, others I have to be in the main/test
directory for them to work. When the tests fail, it’s because a
“require” statement failed - usually for a file that was already
encountered in a require statement in another file. Changing the
“require” to a “load” statement fixes the problem - in some situations.

My solution (remember, I’m a Ruby-Newbie so don’t laugh) was to try
changing the require statements to something like:

load File.dirname(FILE) + “/filename.rb” unless
require File.dirname(FILE) + ‘filename’

With this, I’m able to run the test from any directory (even from “/”).
So, this seems like a really good solution. I only use “load” if
“require” fails and I ensure that Ruby can always find the files it
needs.

My question is whether using this “load unless require” approach will
lead to other problems? Would making this change result in some bad
mojo somewhere down the line?

todd wrote:

My solution (remember, I’m a Ruby-Newbie so don’t laugh) was to try
changing the require statements to something like:

load File.dirname(FILE) + “/filename.rb” unless
require File.dirname(FILE) + ‘filename’

Oops. Require will return false if the file is already loaded, not if
the require fails. So this is probaby NOT what you want.

One solution is to run your tests via rake. Rake will always run its
tasks from the directory that contains the Rakefile. This means you
invoke rake from any project directory and be assured that the run is
consistent.

The project you are working might already have a Rakefile setup. If so,
you might be able to say “rake test” to run the tests.

Otherwise, just create a Rakefile with something along the following
lines:

task :test do
ruby %{-Ilib test/test_file_name.rb}
end

Where “lib” is the local directory containing the project files. By
using -I, we make sure that the project local files are used instead of
whatever might be installed on the machine.

For more sophisticated tasks, rake has a built-in test task that you can
configure according to your needs.

See: http://docs.rubyrake.org/

– Jim W.

With this, I’m able to run the test from any directory (even from “/”).
So, this seems like a really good solution. I only use “load” if
“require” fails and I ensure that Ruby can always find the files it
needs.

My question is whether using this “load unless require” approach will
lead to other problems? Would making this change result in some bad
mojo somewhere down the line?

Jim W. wrote:

Oops. Require will return false if the file is already loaded, not if
the require fails. So this is probaby NOT what you want.

You’re correct! Definately not what I want!

Thanks - I’ll use the rake approach.

Todd