delegate unless nil

An issue came up yesterday that involved an strange nil error, where an attribute was being delegated to a nil association.

I recalled reading this ticket opened by court3nay from caboo.se and thought it might come in handy for others if I put it in the blogosphere.

The ticket ended up being closed because it was deemed unnecessary. Someone with the moniker “protocool” (presumably trevor at http://protocool.com/) shared the final solution which works out of the box with no patches. It goes something like this:


delegate :some_method, :to => '(some_association or return nil)'

The cool thing about this solution, over the proposed patch, is that you can do whatever you like (rather than simply return nil), such as return a default value or raise a custom exception.

actionmailer ActionView ActiveRecord activesupport agile ajax alphadecimal audio autotest BDD blocks capistrano ssh ruby console controller css dashboard widget delegate dog puppy naming name DRM email obfuscation exceptions factories factories-and-workers factory pattern filemerge find and replace finder fink fixtures fun functional testing gem git google maps haml helper helpers imagemagick Intertrust irb javascript jquery jrails logo macro math meetup model openssl OS X patch Pioneer Electronics plugin polymorphism project management prototype.js rails rails gotcha rails,patch,validations railsconf rake rmagick RSA encryption ruby ruby on rails script scrum scrum lessons rails scrumninja shoulda subversion SyncTV TDD testing textmate tips tricks unique hashes unix shell validation view yaml zebra stripes