If you try to evaluate the current date in an ActiveRecord scope, it will likely be incorrect due to this being evaluated when your application code is loaded instead of at runtime. You have to pass this through in a lambda, like this:
scope :today, lambda { where(:submitted_at => Date.today.to_time.utc..(Date.today + 1).to_time.utc) }
That is a funky example because there is conversion to time occurring. Regardless, my question is where else is this a concern? Are ActiveRecord scopes the only place where I can count on my calls to Date not being evaluated at runtime?
When you declare a
scopeyou’re calling thescopemethod on the class itself. This is done , as you said, in loading time and not in runtime.This happens every time you call a method on a class on its declaration. Some examples:
Those are examples of methods which are called on the class itself during its declaration. This means that any of its parameters will be evaluated on loading time and not on runtime.
Let’s take a further example. If you wanted to give the
engineto use for theacts_as_combustion_machineyou’d maybe do something like:Take into account that this would be evaluated during class loading time (same as for the Date).
I guess it helps you clarifying the reason of this a bit more… but please, don’t hesitate to ask if other questions. It took me a bit to understand this myself 😉