Module: NilComparable
- Defined in:
- lib/carat/nil-comparable.rb
Overview
# Calling this method for a given class allows instances # of a class to be compared to nil using <=>. # Adapted from code by Paul Brannan (Ruby License) # NOTE: THIS SHOULD BE A CLASS INCLUDING MODULE, I THINK. def nil_comparable(klass=self)
klass.class_eval %{
if method_defined?( :<=> )
alias_method :compare_without_nil, :<=>
else
def compare_without_nil( other )
raise TypeError, "Cannot compare \#{self.inspect} to \#{other.inspect}"
end
end
def <=>( other )
return 1 if other.nil?
compare_without_nil( other )
end
}
end
Class Method Summary collapse
Class Method Details
.included(mod) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/carat/nil-comparable.rb', line 49 def self.included( mod ) mod.class_eval %{ if method_defined?( :<=> ) alias_method :compare_without_nil, :<=> else def compare_without_nil( other ) raise TypeError, "Cannot compare \#{self.inspect} to \#{other.inspect}" end end def <=>( other ) return 1 if other.nil? compare_without_nil( other ) end } end |