Module: Equitable

Defined in:
lib/standard/facets/equitable.rb

Overview

Equitable

This mixin provides methods of equality based on a single #identity method which must return a list of accessors used as the identity keys.

It also provides a “shortcut” for creating the #identity method based on given accessors and returns the Equitable module for inclusion.

include Equitable(:a, :b)

is equivalent to including a module containing:

def ==(other)
  self.a == other.a && self.b == other.b
end

def eql?(other)
  self.a.eql?(other.a) && self.b.eql?(other.b)
end

def hash()
  self.a.hash ^ self.b.hash
end

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.identify(base, *accessors) ⇒ Object



29
30
31
32
# File 'lib/standard/facets/equitable.rb', line 29

def self.identify(base, *accessors)
  base.send(:define_method, :identity){ accessors }
  self
end

Instance Method Details

#==(o) ⇒ Object



34
35
36
# File 'lib/standard/facets/equitable.rb', line 34

def ==(o)
  identity.all?{ |a| send(a) == o.send(a) }
end

#eql?(o) ⇒ Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/standard/facets/equitable.rb', line 38

def eql?(o)
  identity.all?{ |a| send(a).eql?(o.send(a)) }
end

#hashObject



42
43
44
# File 'lib/standard/facets/equitable.rb', line 42

def hash
  identity.inject(0){ |memo, a| memo ^ send(a).hash }
end