views:

114

answers:

1

If a train leaves less than an hour from now, I want its row in the schedule table to be highlighted red. Currently I'm doing the calculation like this:

if Time.zone.now + 1.hour > t[from_station]
  # do whatever
end

This works and kind of makes sense, but I wonder if there's a clearer / more idiomatic way to express this (I could imagine coming back to this code in a few months and having to pause for a moment to mentally parse Time.zone.now + 1.hour).

+6  A: 

You could use from_now:

if t[from_station] <  1.hour.from_now

When using Time.zone.now, you'll have to specify it, so since is probably more readable (from_now is just an alias to since):

if t[from_station] < 1.hour.since(Time.zone.now)
Pesto
Great answer. Is there any way to make `1.hour.from_now` (which seems like the most correct way to express this) work with the Rails app's default timezone (as defined in environment.rb)?
Horace Loeb
`from_now` takes a single argument. By default it uses `Time.now`. You can, of course, pass it `Time.zone.now` just as I did with `since` (they're actually the same method). If you want `Time.now` set to the correct timezone (so that you don't even have to provide an argument), you have to set `ENV['TZ']` (or the `TZ` environment variable) to the correct timezone, too.
Pesto