Fun with Delegate Methods
30 January 2010Earlier this week, I needed to expose methods on an instance variable in a Rails Model. The details of why I needed to aren't as interesting as the options for implementation. Lets's take a look.
The first option is to create individual methods that delegate to the instance variable. This option is probably the easiest to understand, but verbose. We can do better.
Another option is to use Ruby's method missing. I really liked this option, but it felt too much like black magic, and it didn't leave me with any control of the methods that are being implemented.
How it works: By overriding method missing, we can check to see if our instance variable responds to the method trying to be invoked. If not, we simply call the super. If it does, great, invoke the method via send by passing the method name and params.
The last option, and the one that I chose, is to use Active Support's built in delegate method. While not as cool as method missing, this option lets me control which methods are being exposed. Implementing this is also pretty easy to comprehend.
How it works: Under the covers, the delegate method works in a similar fashion to the method missing option. When called, the delegate method writes out a function(using the send method to pass the parms and a block, to whatever the value of the :to key is in the options hash) and then evaluates the new function with Ruby's module_eval. You can view the full implementation details here (hooray open source!).
Enjoy!
