Module: AttrComparable::ClassMethods
- Defined in:
- lib/attr_comparable.rb
Instance Method Summary collapse
- #attr_compare(*attributes) ⇒ Object
-
#compare_with_nil(left, right) ⇒ Object
like <=> but handles nil values when equal, returns nil rather than 0 so the caller can || together.
Instance Method Details
#attr_compare(*attributes) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/attr_comparable.rb', line 28 def attr_compare(*attributes) attributes = attributes.flatten class_eval "def <=>(rhs)\n\#{attributes.map do |attribute|\n\"self.class.compare_with_nil(self.\#{attribute}, rhs.\#{attribute})\"\nend.join(\" || \")\n} || 0\nend\n" end |
#compare_with_nil(left, right) ⇒ Object
like <=> but handles nil values when equal, returns nil rather than 0 so the caller can || together
14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/attr_comparable.rb', line 14 def compare_with_nil(left, right) if left.nil? if right.nil? nil else -1 end elsif right.nil? 1 else (left <=> right).nonzero? end end |