A Bug, Today Only
I had to debug some tests that just started failing first thing this morning. I guess I should have procrastinated though, because they would have magically fixed themselves tomorrow morning. The cause of the one day only bug: Leap Year Day, of course.
If you run the following code on a day like today, February 29th 2008,
Date will choke on your invalid date:
require "date" class Date # Returns a Date in the past +year_offset+ years ago. def self.years_ago(year_offset) now = today Date.civil(now.year - year_offset, now.month, now.day) end end puts Date.years_ago(1)
I came up with the following fix, which is accurate enough for my purposes:
require "date" class Date # Returns a Date in the past +year_offset+ years ago. def self.years_ago(year_offset) today - 365 * year_offset end end puts Date.years_ago(1)
I'm not 100% sure that covers all cases though, so use with caution. Date's are tricky business!
Robert Pierce March 1st, 2008 Reply Link
James, that would have made a great practical example for the "why" of Test Driven Development on the closing day of our Ruby Studio. Not sure when in the day you posted this, but if I had read my feeds earlier I might have been able to look smarter in class! :)
Seriously, this is a great supporting example of why TDD is such a good discipline to adopt and follow. Thanks for being open and transparent with examples like this; it's just what newer programmers (like myself) need.