Return an Enumerator from each* methods when no block is given

This commit is contained in:
David Cornu 2018-01-29 13:12:42 -05:00
parent 0b7b54119b
commit bc87711f9c
8 changed files with 54 additions and 2 deletions

View File

@ -99,12 +99,14 @@ module Oga
end
# @see [Oga::XML::Node#each_ancestor]
def each_ancestor(&block)
def each_ancestor
return to_enum(:each_ancestor) unless block_given?
return unless element
yield element
element.each_ancestor(&block)
element.each_ancestor { |ancestor| yield ancestor }
end
private

View File

@ -180,6 +180,8 @@ module Oga
#
# @yieldparam [Oga::XML::Node]
def each_ancestor
return to_enum(:each_ancestor) unless block_given?
node = parent
while node.is_a?(XML::Element)

View File

@ -53,6 +53,8 @@ module Oga
#
# @yieldparam [Oga::XML::Node]
def each
return to_enum(:each) unless block_given?
@nodes.each { |node| yield node }
end

View File

@ -27,6 +27,8 @@ module Oga
#
# @yieldparam [Oga::XML::Node] The current node.
def each_node
return to_enum(:each_node) unless block_given?
visit = children.to_a.reverse
until visit.empty?

View File

@ -211,5 +211,17 @@ EOF
.to yield_successive_args(child, parent)
end
end
describe 'without a block' do
it 'returns an enumerator' do
child = Oga::XML::Element.new(:name => 'b')
parent = Oga::XML::Element.new(:name => 'a', :children => [child])
attr = described_class.new(:name => 'class', :element => child)
enum = attr.each_ancestor
expect(enum).to be_a(Enumerator)
expect(enum.to_a).to eq([child, parent])
end
end
end
end

View File

@ -63,6 +63,18 @@ describe Oga::XML::NodeSet do
expect(yielded).to eq([n1, n2])
end
describe 'without a block' do
it 'returns an enumerator' do
n1 = Oga::XML::Element.new(:name => 'a')
n2 = Oga::XML::Element.new(:name => 'b')
set = described_class.new([n1, n2])
enum = set.each
expect(enum).to be_a(Enumerator)
expect(enum.to_a).to eq([n1, n2])
end
end
end
describe 'Enumerable behaviour' do

View File

@ -289,5 +289,13 @@ describe Oga::XML::Node do
expect { |b| @child2.each_ancestor(&b) }
.to yield_successive_args(@child1, @root)
end
describe 'without a block' do
it 'returns an enumerator' do
enum = @child2.each_ancestor
expect(enum).to be_a(Enumerator)
expect(enum.to_a).to eq([@child1, @root])
end
end
end
end

View File

@ -40,5 +40,17 @@ describe Oga::XML::Traversal do
expect(names).to eq(%w{books book2 title2})
end
describe 'without a block' do
it 'returns an enumerator' do
enum = @document.each_node
expect(enum).to be_a(Enumerator)
names = enum.to_a.map do |node|
node.is_a?(Oga::XML::Element) ? node.name : node.text
end
expect(names).to eq(%w{books book1 title1 Foo book2 title2 Bar})
end
end
end
end