In a rails app, I have model code of the form:
def do_stuff(resource)
models = Model.where(resource: resource)
operated_at = DateTime.now
models.each { |model| some_operation(model, operated_at) }
some_other_operation models, operated_at
end
def some_operation(model, operated_at)
model.date_time_field = operated_at
model.save
end
def some_other_operation(models, operated_at)
models.each do |model|
if model.date_time_field < operated_at
# do something
end
end
end
The 'do something' block of some_other_operation will always be executed, in this situation. Even stranger, if I set this up in the console without all the defined functions, the comparison works as expected. Example:
> model = Model.first
> time_var = DateTime.now
> model.last_imported_at = time_var
=> Fri, 25 Oct 2013 21:14:06 +0000
> model.save
=> true
> model.last_imported_at < time_var
=> false
> model.last_imported_at == time_var
=> true
Finally, if, in some_other_operation
I instead compare in the following way:
if model.date_time_field.to_i < operated_at.to_i
# do something
end
the 'do something' block is reached only when expected. I suspect this is because the to_i
method will drop the fractions of a second defined on the DateTime object, and the operated_at
variable is actually being redefined as DateTime.now
for each methods' scope. If this is the case, then I guess my question is how do I force operated_at
to not be redefined for each scope?