How to require an entire directory of files at path/to/rails/lib in environment.rb?


I searched through the group, but I can't seem to find any reference
for this.

I understand that if files are named in lowercase, classes are named
according to rails convention, and placed in lib directory, they will
be required automatically.



class Item ... end

However, what if I would like to create a directory in /lib?
Currently, I am requiring each file in the dir individually, but I
foresee that the number of files in this dir would grow, and I would
like the require statement in environment.rb to just include the
entire dir, instead of having to include each individual file. Is this

Example (Current)

require 'products/item1'
require 'products/item2'

Can I do this instead?
require 'products/*'

Thanks in advance!!


Well, the simple technical answer, not tested:

    def require_tree(name)
      path_to_lib = "RAILS_ROOT/lib" #adjust if necessary
      path_to_tree = "#{path_to_lib}/#{name}"
      Dir["#{path_to_tree}/**/*.rb"].each { |fn|
          fn =~ /^#{Regexp.escape(path_to_lib)}\/(.*)\.rb$/
          require $1

    # Usage
    require_tree "products"


Excuse me if I’m mistaken, but are you finding all .rb files in a certain directory, and then checking to see if their extension is .rb? Isn’t this kind of irrelevant if you’d already found them?

The regex is there to pick out the "feature name" of
path. The name (called "feature") you pass to require
is stored in $", so that when the same feature is required
a second time, it won't be loaded again.

Now if we pass "/home/foo/my_app/lib/my/class.rb" to
require and some other file does a plain require "my/class",
the file will be loaded two times. My regex picks the
"my/class" out of the full path. There is no conditional -
the regex is just there to destructure the path.

(There's mistake in my original version: The line
'path_to_lib = "RAILS_ROOT/lib" ...' should read
'path_to_lib = "#{RAILS_ROOT}/lib" ...'