Added XML::Node#each_ancestor

This method can be used to walk through the ancestor tree of a Node.
This commit is contained in:
Yorick Peterse 2015-07-18 01:05:06 +02:00
parent db39b25546
commit 52741a3b78
2 changed files with 34 additions and 0 deletions

View File

@ -214,6 +214,26 @@ module Oga
def xml?
!html?
end
##
# Yields all ancestor elements of the current node.
#
# @example
# some_element.each_ancestor do |node|
# # ...
# end
#
# @yieldparam [Oga::XML::Node]
#
def each_ancestor
node = parent
while node.is_a?(XML::Element)
yield node
node = node.parent
end
end
end # Element
end # XML
end # Oga

View File

@ -276,4 +276,18 @@ describe Oga::XML::Node do
node.xml?.should == false
end
end
describe '#each_ancestor' do
before do
@child2 = Oga::XML::Element.new(:name => 'c')
@child1 = Oga::XML::Element.new(:name => 'b', :children => [@child2])
@root = Oga::XML::Element.new(:name => 'a', :children => [@child1])
@document = Oga::XML::Document.new(:children => [@root])
end
it 'yields all the ancestor elements' do
expect { |b| @child2.each_ancestor(&b) }
.to yield_successive_args(@child1, @root)
end
end
end