1

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?

Blastula
  • 494
  • 6
  • 17

1 Answers1

2

When you declare a scope you're calling the scope method 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:

class Car < ActiveRecord::Base
  acts_as_combustion_machine
  belongs_to :driver
  has_many :wheels
end

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 engine to use for the acts_as_combustion_machine you'd maybe do something like:

acts_as_combustion_machine Engine.first

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 ;)

Fran
  • 1,073
  • 10
  • 19
  • Thanks for the excellent answer. My immediate motivation for asking was not let the same 'date inside a scope' mistake happen in my validations. For example, using Date.today inside a validate block. It seems that this is not a concern because the validation is evaluated in the ActiveRecord object's lifecycle at runtime. – Blastula Feb 21 '12 at 19:06