Pregunta

I know if I'm using scoped methods in a Rails model, I should store the query in a proc object so it's evaluated when I call it, and not when the application is launched. Example:

scope :shifts_last_week, -> { where(date: (Date.today - 7)..(Date.today)) }

Is the same kind of process necessary for class methods in the same model? Are those methods evaluated at launch in the same way, or can I just define the method as follows?

def self.shifts_this_week
  where( date: (Date.today.beginning_of_week(WEEK_START))..(Date.today + 1) )
end
¿Fue útil?

Solución

The answer is that you do not have to do the same lambda wrapping for class method definitions, which are only executed when the method itself is called. The reason why scope is executed when you run the application is because scope is itself a method which ends up calling the 'where' clause (rather than just being a method definition). Method definitions themselves do not get executed until the method they define is called.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top