require_all
A wonderfully simple way to load your code.
http://github.com/tarcieri/require_all/tree/master
Tired of futzing around with require statements everywhere, littering
your
code with require File.dirname(FILE) crap? What if you could just
point
something at a big directory full of code and have everything just
automagically load regardless of the dependency structure?
Wouldn’t that be nice? Well, now you can!
require ‘require_all’
You can now require_all in a multitude of different ways:
require_all *args
One of the easiest ways to require_all is to give it a glob, which will
enumerate all the matching files and load them in the proper order. For
example, to load all the Ruby files under the ‘lib’ directory, just do:
require_all ‘lib/**/*.rb’
If the dependencies between the matched files are unresolvable, it will
throw the first unresolvable NameError.
Don’t want to give it a glob? Just give it a list of files:
require_all Dir.glob(“blah/**/*.rb”).reject { |f| stupid_file(f) }
Or if you want, just list the files directly as arguments:
require_all ‘lib/a.rb’, ‘lib/b.rb’, ‘lib/c.rb’, ‘lib/d.rb’
It’s just that easy! Code loading shouldn’t be hard.
Methodology
I didn’t invent the approach this gem uses. It was shamelessly stolen
from
Merb. Once upon a time at MountainWest RubyConf we were discussing how
horrible ActiveSupport’s dependencies.rb hijacking of const_missing and
someone described the approach Merb used to me. It was so simple and
clean!
Here’s how it works:
- Enumerate the files in the glob
- Try to load all of the files. If we encounter a NameError loading
a
particular file, store that file in a “try to load it later†list. - If all the files loaded, great, we’re done! If not, go through the
“try to load it later†list again rescuing NameErrors the same way. - If we walk the whole “try to load it later†list and it doesn’t
shrink
at all, we’ve encountered an unresolvable dependency. In this case,
require_all will rethrow the first NameError it encountered.
Questions? Comments? Concerns?
You can reach the author on github or freenode: “tarcieriâ€
Or by email: [email protected]
Got issues with require_all to report? Post ‘em here:
Github Tracker http://github.com/tarcieri/require_all/issues
License
MIT (see the LICENSE file for details)