Bryan
Bryan

Reputation: 3280

How to DRY up shared scopes for Mongoid models?

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?

Upvotes: 0

Views: 361

Answers (1)

twooface
twooface

Reputation: 450

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

Upvotes: 2

Related Questions