Extreme named_scope?
By now, we all know that named_scope is one of the most useful Rails features ever. It’s the kind of thing that makes me wonder how I ever lived without it. I’m currently refactoring some old code and finding that using named_scope can make for some really long chains sometimes. They almost seem…too long.
For instance, I have an Update model which contains both news items (short blurbs) and articles (longer updates). Some articles are also for internal eyes only (via admin pages). When someone is viewing a news item, the 5 latest updates appear in the sidebar, but I can’t be listing the one they’re currently viewing!
In the tradition of small view / huge model, I’ve attempted to move all the logic into the model.
Model / update.rb
1 2 3 4 5 | named_scope :public, :conditions => "internal_only = 0", :order => 'updated_at desc' named_scope :news, :conditions => "update_type = 'news'" named_scope :articles, :conditions => "update_type = 'article'" named_scope :limit_to, lambda { |l| { :limit => l } } named_scope :except, lambda { |i| { :conditions => [ "id != ?", i ] } } |
In a view or helper method (object = currently displayed item)
1 2 | news = Update.public.news.limit_to(5).except(object.id) articles = Update.public.articles.limit_to(5).except(object.id) |
Now, this works great, but that’s getting to be a mighty long scoping chain. So, the burning question - can this chain ever get too long?
