From: Luke Kanies Date: 2006-08-02T07:22:33+09:00 Subject: Re: Strategies for autoloading ruby files Brian Palmer wrote: > You can use `Module.const_missing` to autoload a file the first time the > class in that file is mentioned in the code. So you could write an > `Object.const_missing(name)` method that translates the constant into a > file name of an expected format, then load that file on-the-fly. Ironically, I use almost no constants in my code. Parent classes get constants, but subclasses are almost always created dynamically[1], like so: Puppet::Type.newtype(:user) do ... end Then I always refer to that class by the name 'user' and never by the constant. This is partially because it's easier for me, but also because I've written a custom language (no, not a DSL[2]) for Puppet, and most of those names are exposed in that language. E.g., you create a 'user' type like above, and users can create user elements in Puppet: user { luke: comment => "Luke Kanies", uid => 100, shell => bash, ensure => exists } Puppet supports lots of package types (e.g., dpkg, apt, rpm, darwinports, gems) and service types (init, smf, etc.); I specify the name when I create the class, and users can select those types by name, either in the language or directly in Ruby if they're directly accessing the library. In other words, my problem is not how to hook into the autoload, it's the guts behind it. > Amusingly, this is exactly the code example that's given in the Pickaxe > version 2 under Module.const_missing, along with a note that the code is > in very poor style and is a "perverse kind of autoload functionality". 1 - I do assign constants to them, but only because class inspection during error printing did not work consistently unless there's a constant assigned to the class. I just tried reproducing this but could not; I don't remember the details well enough, I guess. 2 - See the FAQ, http://reductivelabs.com/projects/puppet/faq.html, the fourth question. -- An expert is a person who has made all the mistakes that can be made in a very narrow field. - Niels Bohr --------------------------------------------------------------------- Luke Kanies | http://reductivelabs.com | http://madstop.com