Where the Required Things Are (#175)

I’ve had a go at a solution, but I don’t think what I did works
properly.
Feel free to comment on what’s wrong with it.

RUBYGEMS = ‘rubygems.rb’

Create a copy of the load path ($:)

@load_path = Array.new($:)

Replace ‘.’ in @load_path with full directory path

@load_path[@load_path.index(‘.’)] = Dir.pwd

Enforcing the require of rubygems before aliasing Kernel#require makes

things

less troublesome.

begin
# If rubygems has been loaded, append the its path(s)
@load_path.concat(Gem.path) if require RUBYGEMS
rescue LoadError
# A LoadError will occur if rubygems isn’t installed, but it should
be
safe
# to ignore.
end

module Kernel
alias :old_require :require

# Make our own require method that uses '@load_path' variable to 

find
the path
# of the file given by ‘string’
def require(string)
old_require string

    # If 'string' doesn't have an extension
    if File.extname(string).empty?
        exts = ['.rb', '.so', '.o', '.dll']
        until exts.empty?
            fname = string + exts.shift
            path = @load_path.find { |i| File.exists? File.join(i,

fname) }
return File.join(path, fname) unless path.nil?
end
else
return @load_path.find { |i| File.exists? File.join(i,
string) }
end
raise "If you can read this, Kernel#require was able to find a
library " +
“named #{string} but #{FILE} was not able to. Either
there is” +
"bug in #{FILE} and/or Kernel#require’s search
method is
" +
“different to #{FILE}'s”
end
end

if $0 == FILE
ARGV.each { |a| puts require(a) }
end

2008/8/29 Matthew M. [email protected]