views:

33

answers:

3

Hi there,

I know the following model code is not correct: as models get loaded only on server boot, time "constants" are loaded at that time only, too.

class Article < ActiveRecord::Base

  def expiring?
    if (self.enddate - Time.now) <= 1.day
      true
    else
      false
    end
  end

end

What do I have to correct how, so that the time values get evaluated everytime "expiring?" is called?

Thanks for your help!

Tom

+2  A: 

Models are loaded on server boot, but methods are called when they are called. If you're talking about 1.day, then 1.day isn't ever going to change (unless they change the number of seconds in a day) so you don't need to worry about that only being 'loaded' once.

Skilldrick
Thanks for your quick answer!I was only referring to: (self.enddate - Time.now).So, if I'm not mistaken, this must be corrected only if we're talking about "named_scope"s **in** models...?
TomDogg
A: 
if (self.enddate <= Date.today)

Could this may be the solution ?

MrJack
A: 

Unless I'm missing something I don't see anything wrong with the code you've given. Time.now will get evaluated every time expiring? is called. I'd probably shorten to:

def expiring?
  self.enddate >= 1.day.from_now
end

For a named scope you'd need to put it into a lambda so it does get evaluated every time (this sounds like the question you're actually asking):

named_scope :expiring, lambda { {:conditions => ["enddate >= ?", 1.day.from_now ] } } 
Dave Sims
Thanks! That answers everything!
TomDogg