Class: Canon::TreeDiff::Core::AttributeComparator

Inherits:
Object
  • Object
show all
Defined in:
lib/canon/tree_diff/core/attribute_comparator.rb

Overview

AttributeComparator provides order-independent attribute comparison

This class encapsulates the logic for comparing node attributes in a way that respects match options, particularly attribute_order.

Key responsibilities:

  • Compare attributes with configurable order sensitivity

  • Provide hash-based equality for matching algorithms

  • Support both strict and normalized comparison modes

Examples:

comparator = AttributeComparator.new(attribute_order: :ignore)
attrs1 = {class: "TOC", id: "_"}
attrs2 = {id: "_", class: "TOC"}
comparator.equal?(attrs1, attrs2) # => true

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attribute_order: :strict) ⇒ AttributeComparator

Initialize comparator with match options

Parameters:

  • attribute_order (Symbol) (defaults to: :strict)

    :strict or :ignore/:normalize



28
29
30
# File 'lib/canon/tree_diff/core/attribute_comparator.rb', line 28

def initialize(attribute_order: :strict)
  @attribute_order = attribute_order
end

Instance Attribute Details

#attribute_orderObject (readonly)

Returns the value of attribute attribute_order.



23
24
25
# File 'lib/canon/tree_diff/core/attribute_comparator.rb', line 23

def attribute_order
  @attribute_order
end

Instance Method Details

#comparison_hash(attrs) ⇒ Hash

Generate a comparison hash for attribute matching

This is used by hash-based matchers to ensure nodes with equivalent attributes (according to match options) get the same hash value.

Parameters:

  • attrs (Hash)

    Attribute hash

Returns:

  • (Hash)

    Normalized hash for comparison



62
63
64
65
66
67
68
69
70
# File 'lib/canon/tree_diff/core/attribute_comparator.rb', line 62

def comparison_hash(attrs)
  return {} if attrs.nil? || attrs.empty?

  if attribute_order == :strict
    attrs
  else
    normalize_for_comparison(attrs)
  end
end

#equal?(attrs1, attrs2) ⇒ Boolean

Compare two attribute hashes for equality

Parameters:

  • attrs1 (Hash)

    First attribute hash

  • attrs2 (Hash)

    Second attribute hash

Returns:

  • (Boolean)

    True if attributes are considered equal



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/canon/tree_diff/core/attribute_comparator.rb', line 37

def equal?(attrs1, attrs2)
  # Handle nil/empty cases
  return true if attrs1.nil? && attrs2.nil?
  return false if attrs1.nil? || attrs2.nil?

  attrs1 = attrs1.to_h if attrs1.respond_to?(:to_h)
  attrs2 = attrs2.to_h if attrs2.respond_to?(:to_h)

  if attribute_order == :strict
    # Strict mode: order matters
    attrs1 == attrs2
  else
    # Ignore/normalize mode: sort keys for comparison
    normalize_for_comparison(attrs1) == normalize_for_comparison(attrs2)
  end
end