Sha256: 507d1a76642fc0c6b5088bf2268bbd78606215067c19234b4400cf562d29dbcd
Contents?: true
Size: 1.98 KB
Versions: 2
Compression:
Stored size: 1.98 KB
Contents
require 'traitorous' module Traitorous # 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 module Equality # Override the normal :== method to compare each trait individually when # testing equality. # # Coordinate.new(x: 1, y: 2) == Coordinate.new(x:1, y: 2) # @param other_val [#traits] target of comparison # @return Boolean if all traits values match return true. 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 # compare the equality of 2 arrays, and I'm not sure this is the best way to # do the comparisons. # @params alpha [Array] first array # @params beta [Array] second array # @return [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?) 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 end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
traitorous-0.2.2 | lib/traitorous/equality.rb |
traitorous-0.2.0 | lib/traitorous/equality.rb |