Thursday, April 10, 2008

Merb boot order

So, for the better part of a day, I've been really focused on the load sequence of Merb to understand the order in which the resources are loaded. Here's a summary of my understanding of the bootloader code.

The BootLoader class has a clean design for defining the initialization sequence, it just took me a while to get that 'ahhh' moment. Probably because I'm a moron.

In bootloader.rb, there are several sub-classes of Merb::BootLoader defined. As each subclass is instantiated, they are pushed into an array of subclasses via the inherited method on the Merb::BootLoader class. When the run method in Merb::BootLoader is called the subclass array is processed and the run method of each subclass is called. Very nice setup.

So, here's a list of the classes in the order they will be processed. The names should be decriptive enough to give you an idea of their functionality:
  1. Merb::BootLoader::Logger
  2. Merb::BootLoader::DropPidFile
  3. Merb::BootLoader::BuildFramework
  4. Merb::BootLoader::Dependencies
  5. Merb::BootLoader::BeforeAppRuns
  6. Merb::BootLoader::LoadClasses
  7. Merb::BootLoader::Templates
  8. Merb::BootLoader::MimeTypes
  9. Merb::BootLoader::AfterAppLoads
  10. Merb::BootLoader::MixinSessionController
  11. Merb::BootLoader::ChooseAdapter
  12. Merb::BootLoader::RackUpApplication
  13. Merb::BootLoader::ReloadClasses
  14. Merb::BootLoader::ReloadTemplates

The Merb::BootLoader::Dependencies class does a few actions that can't be inferred from the name. The run method on this class calls the following (in this order):
  • load_initfile
  • load_env_config
  • enable_json_gem
  • load_dependencies
  • update_logger
The part that confused me was the two callbacks defined as before_load and after_load. They would be called in init.rb as:
Merb::BootLoader.before_app_loads do
#Stuff you want to do before your application loads
end

Merb::BootLoader.after_app_loads do
#Stuff you want to do after you application loads
end

What was confusing me was the reference to app. It seems clear now, but I was thinking this included everything: the Merb framework classes and the application classes (models, controllers, etc...) you write. This actually refers to your application code. Do stuff before Merb loads your code or do it after.

The before_app callbacks are processed in the run method of Merb::BootLoader::BeforeAppRuns. As you can see from above, this is before the Merb::BootLoader::LoadClasses. This is the class that processes everything in the load paths for your application. The Merb::BootLoader::AfterAppLoads processes the after_load callbacks.

My initializers post has been updated to reflect this new information.

I hope someone will find this useful.

back to Merb index

0 comments: