Module: AttrComparable::ClassMethods

Defined in:
lib/attr_comparable.rb

Instance Method Summary collapse

Instance Method Details

#attr_compare(*attributes_arg) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/attr_comparable.rb', line 31

def attr_compare(*attributes_arg)
  attributes = attributes_arg.flatten

  remaining_attrs = attributes.size;
  attr_exprs = attributes.map do |attribute|
    remaining_attrs -= 1
    compare_with_nil_code("self.#{attribute}", "rhs.#{attribute}", remaining_attrs.nonzero?).strip
  end

  class_eval <<-EOS
    def <=>(rhs)
      #{ attr_exprs.join(" || ") }
    end
  EOS
end

#compare_with_nil_code(left, right, return_nil_on_equal) ⇒ Object

like <=> but handles nil values returns the code in string form to be eval’d code will return nil instead of 0 for equal iff return_nil_on_equal is truthy



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/attr_comparable.rb', line 15

def compare_with_nil_code(left, right, return_nil_on_equal)
  <<-EOS
    if #{ left }.nil?
      if #{ right }.nil?
        #{ return_nil_on_equal ? 'nil' : '0' }
      else
        -1
      end
    elsif #{ right }.nil?
      1
    else
      (#{ left } <=> #{ right })#{ '.nonzero?' if return_nil_on_equal }
    end
  EOS
end