Rails中使用好named_scope与时间区间

在我最近的工作中,由于要做数据统计,与时间区间打交道非常多,如统计这个月的销售量之类的。
Message.find(:all, :conditions => {:created_at => Time.now.beginning_of_month..Time.end_of_month})

对于爱美的程序员来说,这看起来不养眼,也不符合DRY精神。写成这种形式感觉 怎么样呢:
Message.in(:this_month) # 在一个named_scope中


来看看是如何做到这么DSLful的吧!

在config/initializer目录中创建timeranges.rb文件,如下:
# timeranges.rb
TimeRanges = {
  :today      => lambda { Time.now.beginning_of_day..Time.now.end_of_day },
  :yesterday  => lambda { 1.day.ago.beginning_of_day..1.day.ago.end_of_day },
  :this_week  => lambda { Time.now.beginning_of_week..Time.now.end_of_week },
  :last_week  => lambda { 1.week.ago.beginning_of_week..1.week.ago.end_of_week},
  :this_month => lambda { Time.now.beginning_of_month..Time.now.end_of_month },
  :last_month => lambda { 1.month.ago.beginning_of_month..1.month.ago.end_of_month }
}


在Model中创建一个名为in的named_scope:
class Message < ActiveRecord::Base
  named_scope :in, lambda { |period| 
      :conditions => {:created_at => TimeRanges[period].call}
  }
end


一个字,爽!

参考: http://workswithruby.com/2009/2/application-wide-timeranges-3

你可能感兴趣的:(工作,Ruby,Rails,ActiveRecord,idea)