Module: Traitorous::Equality

Defined in:
lib/traitorous/equality.rb

Overview

Provides a mechanism to test equality of objects that implement a traits hash. This is an iffy concept, and if I didn’t happen to be using a Coordinate object in te project this was extracted from it probably wouldn’t be a part

For this module to work it makes a set of assumptions.

  1. The base assumption of the types of objects created using Traitorous is that they are easily expressed in text.

  2. That the aggregate of the traits equality means the 2 are equal

  3. If a trait is an Array, each element of the array is tested against the 2nd, and vice versa.

  4. all other equality is tested using ==

  5. nested objects should also implement equality to facilitate the comparisons of deeply nested structures

Further expansions might call for the converter to assume an equality guise

Instance Method Summary collapse

Instance Method Details

#==(other_val) ⇒ Object

Returns Boolean if all traits values match return true.

Parameters:

  • other_val (#traits)

    target of comparison

Returns:

  • Boolean if all traits values match return true.



27
28
29
30
31
32
33
34
# File 'lib/traitorous/equality.rb', line 27

def ==(other_val)
  return false unless self.class == other_val.class
  traits.keys.all? do |trait_name|
    orig_trait  =      self.send(trait_name.intern)
    other_trait = other_val.send(trait_name.intern)
    array_equality(orig_trait, other_trait) || (orig_trait == other_trait)
  end
end

#array_equality(alpha, beta) ⇒ Boolean

compare the equality of 2 arrays, and I’m not sure this is the best way to do the comparisons.

Returns:

  • (Boolean)

    true if every element in 1 array is equal(==) to an element in the 2nd and vice versa (order doesn’t matter, should it?)



50
51
52
53
# File 'lib/traitorous/equality.rb', line 50

def array_equality(alpha, beta)
  return false unless (alpha.is_a?(Array) && beta.is_a?(Array))
  alpha.all?{|a| beta.any?{|b| a == b}}
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/traitorous/equality.rb', line 36

def eql?(other)
  self == other
end

#hashObject



40
41
42
# File 'lib/traitorous/equality.rb', line 40

def hash
  traits.hash
end