Class: EacRubyUtils::CompareBy

Inherits:
Object
  • Object
show all
Defined in:
lib/eac_ruby_utils/compare_by.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fields) ⇒ CompareBy

Returns a new instance of CompareBy.



9
10
11
# File 'lib/eac_ruby_utils/compare_by.rb', line 9

def initialize(fields)
  @fields = fields
end

Instance Attribute Details

#fieldsObject (readonly)

Returns the value of attribute fields.



7
8
9
# File 'lib/eac_ruby_utils/compare_by.rb', line 7

def fields
  @fields
end

Instance Method Details

#apply(klass) ⇒ Object



13
14
15
16
17
18
19
20
21
22
# File 'lib/eac_ruby_utils/compare_by.rb', line 13

def apply(klass)
  pself = self
  klass.include(::Comparable)
  %i[<=> eql?].each do |cmp_method|
    klass.define_method(cmp_method) do |other|
      pself.object_values(self).send(cmp_method, pself.object_values(other))
    end
  end
  klass.define_method(:hash) { pself.object_values(self).hash }
end

#object_values(object) ⇒ Object



24
25
26
# File 'lib/eac_ruby_utils/compare_by.rb', line 24

def object_values(object)
  fields.map { |field| object.send(field) }
end