If you find yourself checking for nil constantly, a null object of some sort can help.
I wanted to make a null object for dates. Here is the NullDate class I came up with.
class NullDate
include Comparable
def strftime format
"No date yet."
end
def to_s
"No date yet."
end
def <=>(other_date)
Time.new(0000,1,1) <=> other_date
end
def to_datetime
Time.new(0000,1,1).to_datetime
end
end
I found myself checking for nil all over the place when comparing dates, so I
made my NullDate class implement <=>, and just have it compare to
Time.new(0000,1,1)
, which is the lowest time/date value possible. Be sure to
implement to_datetime
, or you’ll get an error like this:
Here’s an ascii.io screencast I made that demonstrates use of this class!