Rails, Firefox, Anime, Mac
In: General
9 Dec 2007Time#advance and DateTime#advance just got, erm, more betterer in Rails 2.0.
In Rails 1.2.6 and earlier, Time#advance and DateTime#advance only accepted :year, :month and :day options. You’d think :hours, :minutes and :seconds would work too but due to a bug in the code (see ticket #9818), you get something like this instead:
time = Time.utc(2000,10,1,10,30,45)
# => Sun Oct 01 10:30:45 UTC 2000
time.advance(:days =>3, :hour => 2)
# => Wed Oct 04 02:00:00 UTC 2000
Notice how the hour is changed instead of being advanced.
Now, thanks to Geoff Buesing’s efforts, passing :hours, :minutes and :seconds options work as you’d expect:
time = Time.local(2005,2,28,15,15,10)
# => Mon Feb 28 15:15:10 0800 2005
time.advance(:hours => 5, :minutes => 20, :seconds => 25)
# => Mon Feb 28 20:35:35 0800 2005
Hell, you can even #advance by :weeks (see ticket #9866):
time = Time.local(2005,2,28,15,15,10)
# => Mon Feb 28 15:15:10 0800 2005
time.advance(:weeks => 2)
# => Mon Mar 14 15:15:10 0800 2005
+1 for consistency and properly behaving code. Thanks to this #advance patch, Geoff was also able to re-use #advance to refactor some other parts of ActiveSupport’s time-related extensions.
Geoff Buesing is a regular Rails contributor and I’ve known him to be the date/datetime/time guru – just look at his submitted patches if you’re not convinced. Not too long ago Geoff was given well-deserved commit rights (congrats Geoff)! You won’t find him on the Ruby on Rails Core team page yet though – it’s probably out of date.
Check out his blog at mad.ly where he writes mostly his adventures with on unobtrusive JavaScript in Rails.
4 Responses to Time#advance now uses :weeks, :hours, :minutes, :seconds options – Rails 2.0 a feature a day #1
» The Links » roarin’ reporter
December 10th, 2007 at 9am
[...] Time#advance now uses :weeks, :hours, :minutes, :seconds options – Rails 2.0 a feature a day #1 [...]
choonkeat
December 10th, 2007 at 11am
nicely done! good idea on the “about contributor”. looks like i’ll have to look for something to patch!
and i can finally stop following http://twitter.com/railsedge (which i fail to read everything anyways)
Chu Yeow
December 10th, 2007 at 10pm
Well I’ll feature you someday Choon Keat! Anyway, this “column” is about stuff that’s already in gem Rails 2.0.1 – I think you still need to follow railsedge’s Twitter or the Trac timeline/changeset RSS!
Tecker.LOG » Blog Archive » Time#advance???:weeks, :hours, :minutes, :seconds???????Rails 2.0?? #1(??)
June 3rd, 2008 at 12pm
[...] ???Time#advance now uses :weeks, :hours, :minutes, :seconds options – Rails 2.0 a feature a da… [...]