开发者

How to DRY named_scope extension

Given the following code:

  named_scope :by_order, :order => 'priority ASC' do
    def total_points
      self.sum('point_value')
    end
  end

  named_scope :required, :conditions => ['bonus = ?', false] do
    def total_points
      self.sum('point_value')
    end
  end

  named_scope :bonus, :conditions => ['bonus = ?', true] do
    def total_points
      self.sum('point_value')
    end
  开发者_如何学Cend

How would you DRY-up the repeated total_points method?

Environment: Rails 2.3.11


It might be cleaner and more re-usable to define all the scopes separately, and then create class methods for the specific types of collections you need in your application. Here's a quick example (using Rails 3 syntax, but it should be fairly easy to back-port). Note that I've renamed some of the scopes to better reflect what they actually do.

class Thing << ActiveRecord::Base

   scope :in_priority_order, order("priority")
   scope :no_bonus, where(:bonus => false)
   scope :with_bonus, where(:bonus => true)
   scope :total_points, sum(:point_value)

   def self.total_bonus_points
      with_bonus.total_points
   end

   def self.total_no_bonus_points
      no_bonus.total_points
   end
end

BTW I'm not sure why you'd want to combine an order with a sum - the order shouldn't make a difference to the returned values (unless you apply a limit).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜