I have several models that need the same volume. Each of them has a date field expiration_dateon which I want to write a scope.
To preserve DRY stuff, I would like to put the area in a module (in / lib), which I will extend each model. However, when I call scopeinside the module, the method is undefined.
To get around this, I use class_evalwhen the module is turned on:
module ExpiresWithinScope
def self.extended(base)
scope_code = %q{scope :expires_within, lambda { |number_of_months_from_now| where("expiration_date BETWEEN ? AND ?", Date.today, Date.today + number_of_months_from_now) } }
base.class_eval(scope_code)
end
end
Then I perform extend ExpiresWithinScopein my models.
This approach works, but feels a bit hacked. Is there a better way?
source
share