Module: AttrComparable::ClassMethods
- Defined in:
- lib/attr_comparable.rb
Instance Method Summary collapse
- #attr_compare(*attributes) ⇒ Object
-
#compare_with_nil_code(left, right) ⇒ Object
like <=> but handles nil values returns the code in string form to be eval’d.
Instance Method Details
#attr_compare(*attributes) ⇒ Object
33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/attr_comparable.rb', line 33 def attr_compare(*attributes) attr_exprs = (attributes.flatten).map do |attribute| '(' + compare_with_nil_code("self.#{attribute}", "rhs.#{attribute}").strip + ')' end class_eval " def <=>(rhs)\n unless rhs.nil?\n \#{ attr_exprs.join(\".nonzero? || \") }\n end\n end\n EOS\nend\n" |
#compare_with_nil_code(left, right) ⇒ Object
like <=> but handles nil values returns the code in string form to be eval’d
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/attr_comparable.rb', line 14 def compare_with_nil_code(left, right) " if \#{ left }.nil?\n if \#{ right }.nil?\n 0\n else\n -1\n end\n elsif \#{ right }.nil?\n 1\n else\n if (cmp_result = (\#{ left } <=> \#{ right })).nil?\n return nil\n end\n cmp_result\n end\n EOS\nend\n" |