Module: HeadMusic::ValueEquality

Overview

ValueEquality gives a value object structural equality based on a declared list of attributes. Two instances are equal when they are the same class and every declared attribute is equal.

class Stringing
include HeadMusic::ValueEquality
value_equality :instrument_key, :courses
end

Attributes are read with send, so protected or private readers work too.

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



28
29
30
# File 'lib/head_music/value_equality.rb', line 28

def self.included(base)
  base.extend(ClassMethods)
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?



32
33
34
35
36
# File 'lib/head_music/value_equality.rb', line 32

def ==(other)
  return false unless other.is_a?(self.class)

  self.class.value_equality_attributes.all? { |attribute| send(attribute) == other.send(attribute) }
end

#hash ⇒ Object



39
40
41
# File 'lib/head_music/value_equality.rb', line 39

def hash
  [self.class, *self.class.value_equality_attributes.map { |attribute| send(attribute) }].hash
end