Bugs

Posts tagged with "Bugs."
  • 29

    FEB
    2008

    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!