[LRUG] Comparable Null Objects

Tim Craft mail at timcraft.com
Wed Jul 15 08:14:29 PDT 2015


> If I were to define a coercion method, I think it would have to be
> on Date, which feels wrong.

You could implement #coerce in your class. Date already knows how to
compare itself to numeric objects, so if you want NoExpectedDate
objects to appear after Date objects when sorting all you need is a
numeric object bigger than the astronomical Julian day number values
of your dates. It's shorter to write in Ruby than it is in English:

  class NoExpectedDate
    def coerce(date)
      [date, Float::INFINITY]
    end
  end

Together with implementing Comparable that should give you the
behaviour you want. For a more thorough implementation you might want
type checks.

For more of a functional approach you could use nil to represent the
nothingness. The code for dealing with the difference then moves to
the boundaries instead of being encapsulated within a null object
class. So a sort would look like this:

  events.sort_by { |event| event.expected_date || Float::INFINITY }

And your views would look like this:

  <%= event.expected_date || 'Unknown' %>

Both of those cases can be extracted into functions for re-use.

Cheers,
Tim



More information about the Chat mailing list