Module: Dommy::Internal::NodeTraversal

Defined in:
lib/dommy/internal/node_traversal.rb

Overview

Node tree traversal utilities. Centralizes ancestor walking logic to hide Nokogiri implementation details. Prevents duplication of tree traversal code across Observer, EventTarget, etc.

Class Method Summary collapse

Class Method Details

.ancestor_of?(ancestor, node) ⇒ Boolean

Check if ancestor is an ancestor of node.

Returns:

  • (Boolean)


20
21
22
23
# File 'lib/dommy/internal/node_traversal.rb', line 20

def self.ancestor_of?(ancestor, node)
  each_ancestor(node) { |n| return true if n == ancestor }
  false
end

.each_ancestor(node) ⇒ Object

Walk from a node up to document, yielding each ancestor. Stops at Nokogiri::XML::Document (the root).



11
12
13
14
15
16
17
# File 'lib/dommy/internal/node_traversal.rb', line 11

def self.each_ancestor(node)
  current = node.respond_to?(:parent) ? node.parent : nil
  while current && !current.is_a?(Nokogiri::XML::Document)
    yield current
    current = current.respond_to?(:parent) ? current.parent : nil
  end
end

.find_ancestor(node) ⇒ Object

Find the first ancestor matching a predicate. Returns the result of the block, not the node itself.



27
28
29
30
31
32
33
# File 'lib/dommy/internal/node_traversal.rb', line 27

def self.find_ancestor(node)
  each_ancestor(node) { |n|
    result = yield(n)
    return result if result
  }
  nil
end