Tuesday 11 November 2008

Rails 2.1 named scope

The local rails guru pointed me to the new -- well, kind of -- feature of rails 2.1: the named scope.

In short, it's a way to store a query in the model, semantically very clearly.

I used this feature for the local mailserver administration program.

This is the addition to the MailAddres model:

named_scope :kept, :conditions => { :keep => true }
named_scope :unkept, lambda {{ :conditions => ['keep = 0 or keep IS NULL'] } }
named_scope :my_domain, :conditions => { :domain => "my_domain.it" }
named_scope :cadet, lambda {{ :conditions => ['position > 1'] } }
named_scope :personal, lambda {|username, surname| { :conditions => ["local_part = ? or local_part like ?", username, "%"+ActiveSupport::Inflector.parameterize(surname.downcase, '')+"%" ] }}

Now I can use:

UserAccount.find_by_username('test').mail_addresses.my_domain.cadet.personal.unkept

To fetch addresses of the user 'test' which are in my_domain, is not the first address, are personal alias (no functional alias or nicknames) but are not choosen by the user.

No comments: