What is the best way to define the area inside a module in Rails 3?

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?

+3
source share
2 answers

AR3 - DataMapper,

module ExpiresWithinScope
  def expires_within(months_from_now)
    where("expiration_date BETWEEN ? AND ?", 
    Date.today,
    Date.today + number_of_months_from_now) 
  end
end

:

module ExpiresWithinScope
  def expires_within(months_from_now)
    where(:expiration_date => Date.today..(Date.today + number_of_months_from_now))
  end
end

, isl .

+5

- , scope - :

module ExpiresWithinScope
  def self.included(base)
    base.scope :expires_within, lambda { |number_of_months_from_now| 
      base.where("expiration_date BETWEEN ? AND ?", 
        Date.today,
        Date.today + number_of_months_from_now) 
    }
  end 
end

include ExpiresWithinScope
+10

Source: https://habr.com/ru/post/1765159/


All Articles