[LRUG] Comparable Null Objects
Michael Pavling
pavling at gmail.com
Wed Jul 15 05:29:55 PDT 2015
On 15 Jul 2015 15:03, "Duncan Stuart" <dgmstuart at gmail.com> wrote:
>
> Hi LRUG - hopefully an interesting little problem:
>
> I have an Event class which has an "expected_date" attribute.
> Some events don't have an expected date, so like a good little OO
programmer i've created a Null object:
>
> class NoExpectedDate
> def to_s(format=:default)
> "Unknown"
> end
> end
>
> This works great for printing the values, but when it comes to sorting
the list I of course get:
> ArgumentError: comparison of Date with NoExpectedDate failed
>
> If I include Comparable and define <=> then one comparison works, but the
other doesn't :
>
> class NoExpectedDate
> include Comparable
> def to_s(format=:default)
> "Unknown"
> end
> def <=>(other_date)
> 1 # Treat it as after every other date
> end
> end
>
> $ NoExpectedDate.new > Date.today
> => true
>
> $ Date.today > NoExpectedDate.new
> ArgumentError: comparison of Date with NoExpectedDate failed
>
>
Instead of including `Comparable`, set your `NoExpectedDate` class to
inherit from `Date` (keep the overloads of `.to_s` and `.<=>`)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20150715/b5dbf0ce/attachment-0003.html>
More information about the Chat
mailing list