From: Rick DeNatale Date: 2009-03-16T01:36:29+09:00 Subject: Re: Basics of Require --00163616448df8abec04652af77f Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit There's a very nice, underused method of module which can help with loading code on demand. Despite being quite fluent in Ruby, I only found out about it a few weeks ago, thanks to Chad Fowler. It's Module#autoload. It takes two arguments. The first is the NAME of a constant as either a String or a Symbol, the second is a string with the same meaning of the argument to require. What it does is to associate the first argument with the second, and if and when an undefined constant matching the first argument is encountered in the scope of the module, to effectively require the file named by the path argument. It can be used at the top level to autoload definitions of contstants in the global scope. For example # at top level autoload :Foo, 'lib/foo' # this will load lib/foo.rb the first time anyone references ::Foo require 'something.rb' # in file lib/foo.rb class Foo autoload :Bar, 'lib/foo/bar' # loads lib/foo/bar.rb when ::Foo::Bar is referenced when undefined end # in file 'lib/foo/bar.rb' module Foo::Bar # code end # in file 'something.rb' class MyClass < Foo #... end When the 'class Myclass < Foo' is executed, Foo will be undefined, this will trigger the load of 'lib/foo.rb' which is expected to define the constant Foo which it does. Similarly lib/foo/bar.rb would be loaded if an when some code defined ::Foo::Bar as an undefined constant. This is somewhat similar to the automatic class loading built into Rails (actually the ActiveSupport component of rails) using constant_missing, but it's actually built into Ruby, and has been for quite a while. In fact ActiveSupport and the rest of rails is evolving to implement automatic class loading using autoload, which is how I learned about it. Chad was doing a walkthrough of ActiveRecord at RubyRx and showed the new code. -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Twitter: http://twitter.com/RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale --00163616448df8abec04652af77f--