From: trans Date: 2009-06-09T22:06:03+09:00 Subject: Re: require_all 1.0.0: A wonderfully simple way to load your code On Jun 9, 5:21 am, Tony Arcieri wrote: > 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: > >    1. Enumerate the files in the glob >    2. 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. >    3. 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. >    4. 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: t...@medioh.com > > Got issues with require_all to report? Post ‘em here: > > Github Tracker > License require 'facets/kernel/require_all' The idea predates Merb. However, it's always good too see how implementations may have improved over time. Also, I have seen another definition of #require_all floating around that simply loads every .rb file in a given directory. I wonder if both conceptions of this function (glob loading and directory loading) could be integrated into one. Eg. require_all 'some/path' would do the same as require_all 'some/path/*.rb' Cheers, T.