Rails ActiveRecord Instances and ’super’

   By chris on August 8th 2007 in /dev/rails | 834 views

For a class of objects in my database I extract data from one or two ways: the first directly from the database via ActiveRecord, the second from Amazon using Amazon::Ecs.

When the asset calls to Amazon to populate its properties I want to use the Amazon-provided data. When I refrence the asset without calling to Amazon (ie: the data has been cached) then I want to reference AR's properties directly. I don't want to have to make two calls dependent upon the data's source location.

In otherwords, I always want to be able to call

book.title

no matter what.

Turns out ActiveRecord makes this pretty easy:

RUBY:
  1. def title
  2.   return @atts ? @atts.get( 'title' ) || "" : super
  3. end

If there are attributes and an attribute called "title" exists, return that. If attributes don't exist then call the super class's title() which contains the data extracted from the database.

Pretty cool ActiveRecord, pretty cool.

Trackback URI | Comments RSS

Leave a Reply