| Path: | README |
| Last Update: | Sun May 18 18:50:56 -0700 2008 |
AutoCode is a class (and module) loader from Ruby, complete with initialization hooks and reloading. It works as a mixin and uses const_remove for unloading so there can never be any artifacts from prior loads hanging around.
require 'autocode'
module Application
include AutoCode
auto_load true, :directories => [ :configurations, :models, :views, :controllers ]
end
This will attempt to load code dynamically from the given directories, using the module name to determine which directory to look in. Thus, Application::CustomerModel could load the file models/customer_model.rb.
Auto-loaded or created code is automatically reloadable (very useful when debugging running processes). Just call reload on any given module.
*Important*: Only code loaded via *AutoCode* (auto_load or auto_create) will be reloaded.
Sometimes it‘s useful to generate defaults for classes or modules that don‘t exist. This can be particularly powerful when used in combination with auto_loading.
require 'auto_code'
module Application
include AutoCode
%w( Models Views Controllers ).each |name| do
auto_create_module name do
include AutoCode
auto_load true, :directories => [ name.downcase ]
end
end
end
This will auto_create the modules Configurations, Models, Views, and Controllers within the Application module, as they are referenced, and then initialize them so that they will automatically load source files from the corresponding directories.
For example, referencing Application::Models::Customer will cause the file models/customer.rb to be loaded.
Sometimes you want to reopen a class or module and add or change methods, etc. However, in the case of auto-loading or creating unless your code is in an auto_load or auto_create block, it will get clobbered upon reload. You address this using auto_eval which registers blocks against constant names so that auto_create and auto_load can run them after object creation.
require ‘auto_code‘
module Application
include AutoCode
Models.auto_eval(true) do
set_model self.name
end
end
Autoloading and autocreation, along with reloading, can be used to provide sophisticated rules for loading and even generating modules and classes within a given module. These capabilities are increasingly found within frameworks like Rails and Camping, but AutoCode makes it possible to mixin these capabilities into any situation and precisely control how they are applied.
If you have questions or comments, please go to the Waves support forum (which also supports AutoCode, since AutoCode is principally used within Waves) at groups.google.com/group/rubywaves.
(c) 2007 Dan Yoder
Licensed under the MIT License.