Rails: to_prepare executing code before each request
Friday, August 22nd, 2008I have found little or no documentation on this on the net, so here I’m trying to give back a little from what I learnt. Hopefully that will be the beginning of a solution for others.
Rails version: 2.1.0
The problem:
I have certain ActiveRecord models that I want to monkeypatch (i.e. inject functionality to an existing class on runtime). That’s the beauty of dynamic languages, poor Java sods, no need for an AbstractFactoryFactory for j00!
My first approach was to write a script in ./config/initializers that would be invoked on initialization. However, as it turns out, while this works fine for an immediate use of the said monkeypatched object, this wouldn’t work for later instances of this class. In my case, an ActionController method, when calling one of the monkeypatched functionality would raise a NoMethodException.
It took me a bit to realize what was going on and how rails was actually running through its initialization process.
The solution:
Rail’s initialization code has a method called to_prepare which can be invoked in the initialization block. Now looking at the rails source code for initialization, the method requires dispatcher which loads ActionController::Dispatcher and invokes the method to_prepare. Bingo!
What to do next is simple. In my script found in ./config/initializers, the only change i needed to do is to require 'dispatcher' and to monkeypatch as follows:
Done. Profit.