A Bug, Today Only

Posted 2 months ago in The Standard Library.

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 added 1 day later:

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.

Add Your Thoughts

You can use Markdown in the body of your comment to format text and make links.

Note that I reserve the right to edit any content you post here. I typically exercise this right to fix formatting issues. All posts must be approved so spam will never been seen on these pages.

Author:
URL or Email (optional):
Body: