Hi,
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.
E.g.
/lib/item.rb
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
possible?
Example (Current)
/lib/products/item1.rb
/lib/products/item2.rb
…
…
environment.rb
require ‘products/item1’
require ‘products/item2’
…
…
Can I do this instead?
require ‘products/*’
Thanks in advance!!
Winston
2008/3/11, Winston T. [email protected]:
E.g.
possible?
…
…
Can I do this instead?
require ‘products/*’
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
}
end
# Usage
require_tree "products"
Stefan
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?
2008/3/11, Ryan B. (Radar) [email protected]:
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” …’
Stefan