ActiveRecord Delegation and demeter

18 March 2007

A while ago I looked into the various aspects of the laws of demeter sparked by a post I read whilst trying to find out why Mephisto had the word “delegate” sprinkled throughout it.

If you haven’t come across demeter before then its worth reading the post I linked above and the Wikipedia Article

To sum up the concept in one short sentence, the magic that AR gives us that allow us to, for example, say: is a dangerous thing to do. It’s all lovely and magic when its working but as soon as our person doesn’t have an address every reference to that throws a lovely error and promptly blows up our app.

Rails provides a delegate method which seems to have wrongly been assumed to handle this and protect delegated methods from returning nil errors but this isn’t the case. Using delegate you would expect to say:

delegate :city, :to => :address

and then expect to be able to call

without it all blowing up horribly if there is no address object attached to the person.

Well, after moaning about this to Dave we devised a new AR mixin called ar_delegate that lets you safely delegate methods to other classes and protect against the horrible nil errors that occur when you start nesting relationships using AR magic.

Dave has really come up with some lovely syntax that feels Railsey and hopefully we’ll be able to get this into core if it looks like its a good fit (and we write some tests). All credit to Dave for the code, I was merely an IM-advisor as he was writing it.

See ActiveRecord Delegation over at Dave’s blog for a much better write up and links to the plugin.


Sorry, comments are closed for this article.