Application-wide timeranges February 2nd, 2009

In some applications you need to work with time-ranges a lot. Displaying todays messages, a count of all messages that were posted this month, or last month, … ActiveRecord has pretty good support for times and ranges, so you could do it the default way.

Message.find(:all, :conditions => {:created_at => Time.now.beginning_of_month..Time.end_of_month})

And although this works perfectly it’s not very easy on the eyes. It’s also not very DRY since I need this on a lot of models. It’d be a lot better if I could have it in a scope, like this

Message.in(:this_month)

So how do we achieve this?

In our config/initializer folder we have a file called 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 }
}

Which gives us a constant TimeRanges we can use all over the application. So in our Message we define the named_scope in

class Message < ActiveRecord::Base
  named_scope :in, lambda { |period| 
      :conditions => {:created_at => TimeRanges[period].call}
  }
end

Now we could even make this more DRY and make a module that defines the named_scope when it’s included, but in my application I had a lot of different use-cases for the TimeRanges, and didn’t really need the scope a lot. Leave me a note if you want it in a module but don’t know how to, else it’s an exercise for the interested and easily challenged reader ;-)

tags: , , , l

Sorry, comments are closed for this article.