On 5/28/07, Stefan Rusterholz <apeiros / gmx.net> wrote:
> Universal Date/Time comparison is indeed difficult as neither your nor
> mine (below) solution attribute for different TimeZones and/or DST.
> I'd implement a universal comparison like below:
>
> def <=>(other)
>   [year, day_of_year, hour, minute, second] <=> [other.year,
> other.day_of_year, other.hour, other.minute, other.second]
> end

I was just trying to illustrate the need for using case to determine
an object's class.  If we were to use mixins as an alternative, it's
still very complicated because we'll need to redefine Time#<=>,
Date#<=> and so on. Won't we now have to check if
other.is_a?(DateComp) and still handle the cases when
other.is_a?(self.class)... ? I don't see any difference, because now
we're relying on knowing about DateComp instead of Time or Date.

I agree mixins are useful in many cases, but maybe not in this one.
Another way to make code less rigid might be to still use the case
construct but have something that trusts the foreign object to do the
right thing in the default case.  For example

class Date
  def <=> other
    case other
    when self.class # this case is redundant, with the default case below
      self.ajd <=> other.ajd
    when Numeric
      self.ajd <=> other
    else
      if other.respond_to? :ajd
        # hope that other.ajd means the same thing
        self.ajd <=> other.ajd
      else
        nil # causes ArgumentError (from Comparable probably)
      end
    end
  end
end

Then any class that's supposed to represent a date or time can
implement #ajd and be compatable. But we still had to check if other
was an Integer, because defining Numeric#ajd doesn't really make
sense.

Regards,

Erwin