lib/hash_diff/comparison.rb in hash_diff-0.7.0 vs lib/hash_diff/comparison.rb in hash_diff-0.8.0
- old
+ new
@@ -1,74 +1,60 @@
module HashDiff
- class Comparison < Struct.new(:left, :right)
-
+ class Comparison
+ def initialize(left, right)
+ @left = left
+ @right = right
+ end
+
+ attr_reader :left, :right
+
def diff
- @diff ||= differences(left, right)
+ @diff ||= find_differences { |l, r| [l, r] }
end
def left_diff
- @concern = :left
- @left_diff ||= differences(left, right)
+ @left_diff ||= find_differences { |_, r| r }
end
def right_diff
- @concern = :right
- @right_diff ||= differences(left, right)
+ @right_diff ||= find_differences { |l, _| l }
end
- private
+ protected
- def concern
- @concern ||= :both
+ def find_differences(&reporter)
+ combined_keys.each_with_object({ }, &comparison_strategy(reporter))
end
- def clone(left, right)
- self.dup.tap do |inst|
- inst.left = left
- inst.right = right
- end
- end
+ private
- def differences(left, right)
- combined_attribute_keys.reduce({}, &reduction_strategy)
- end
-
- def reduction_strategy
- lambda do |diff, key|
- diff[key] = report(key) if not equal?(key)
- diff
+ def comparison_strategy(reporter)
+ lambda do |key, diff|
+ diff[key] = report_difference(key, reporter) unless equal?(key)
end
end
- def combined_attribute_keys
+ def combined_keys
(left.keys + right.keys).uniq
end
def equal?(key)
left[key] == right[key]
end
def hash?(value)
- value.is_a? Hash
+ value.is_a?(Hash)
end
def comparable?(key)
- hash?(left[key]) and hash?(right[key])
+ hash?(left[key]) && hash?(right[key])
end
- def report(key)
+ def report_difference(key, reporter)
if comparable?(key)
- clone(left[key], right[key]).diff
+ self.class.new(left[key], right[key]).find_differences(&reporter)
else
- report_concern(key)
- end
- end
-
- def report_concern(key)
- case concern
- when :left then right[key]
- when :right then left[key]
- when :both then [left[key], right[key]]
+ reporter.call(left[key], right[key])
end
end
end
end