Search code examples
rubydatemodelmonkeypatching

Monkey Patch Date class the best option?


In my app, I want to support a blank date field as meaning "some indefinite date in the future", both upon entry and viewing. Since I'm storing this in the database and nil sorts before any non-nil date, I decided to monkey-patch the Date class to implement a "max_value" method that returns "1/1/10000" (the date I picked to represent an indefinite date in the future). I have been overloading +, -, to_s, and other operators/methods to behave appropriately with this value. I then added a before_save callback to the model to convert any blank dates to Date.max_value. This all seems to work (with the exception of a few bugs I'm trying to work out), but is there a better way to do this without monkey-patching the class?


Solution

  • The value you are looking for is null. Overriding a base class, like Date is just begging for trouble down the road.

    Do it in the query

    SELECT * FROM Mystery_Events ORDER BY ISNULL(some_event_date,'1/1/10000') ASC
    

    Alternatively, you can use

    ORDER BY (case WHEN some_event_date IS NULL THEN 1 ELSE 0 END), some_event_date, some_other_sorting_field_to_give_order_to_the_nulls ASC