0

I have a few Mongoid model classes that all have a :datetime field. I would like to query these models to find out records that fall under today's date. The query would look like this:

scope today, where(:datetime.gt => DateTime.now.beginning_of_day, :datetime.lt => DateTime.now.end_of_day)

Currently, the above scope code are duplicated within all the model classes. How do I dry this up?

Bryan
  • 3,220
  • 3
  • 26
  • 31

1 Answers1

2

The simples thing is:

module TimeDepedentent
  field :datetime

  scope today, where(:datetime.gt => DateTime.now.beginning_of_day, :datetime.lt => DateTime.now.end_of_day)

  scope yesterday ...
  scope one_month_ago ...
end

class MyModel
  include TimeDepedentent
end
twooface
  • 450
  • 3
  • 10
  • Check out http://stackoverflow.com/questions/4699343/rails-is-that-possible-to-define-named-scope-in-a-module – Nick Oct 31 '13 at 14:47