From 34e2d28bbdb06b8f09079cd28e617ea8890713db Mon Sep 17 00:00:00 2001 From: Yorick Peterse Date: Thu, 31 Jul 2014 18:57:05 +0200 Subject: [PATCH] Document#all_nodes -> Document#each_node This method has been renamed and now yields nodes and their indexes instead of buffering them in a node set. --- lib/oga/xml/document.rb | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/lib/oga/xml/document.rb b/lib/oga/xml/document.rb index 6ea6efe..04dc08b 100644 --- a/lib/oga/xml/document.rb +++ b/lib/oga/xml/document.rb @@ -50,31 +50,33 @@ module Oga end ## - # Returns a NodeSet containing *all* the nodes in the current document. - # Nodes are inserted in the order they appear in the document. + # Traverses through the document and yields every node to the supplied + # block. + # + # @example + # document.each_node do |node, index| + # p node.class + # end # # This method uses a breadth first search for tree traversal. See # http://en.wikipedia.org/wiki/Breadth-first_search for more information. # - # THINK: Turn into an actual search instead of returning everything? + # @yieldparam [Oga::XML::Node] The current node. + # @yieldparam [Fixnum] The current node's index. # - # @return [Oga::XML::NodeSet] - # - def all_nodes - nodes = NodeSet.new + def each_node visit = children.to_a.dup # copy it since we're using #pop below. + index = 0 until visit.empty? current = visit.pop - nodes << current + yield current, index - current.children.each do |child| - visit << child - end + index += 1 + + current.children.each { |child| visit << child } end - - return nodes end ##