Added XML::Element#text_nodes.

This method returns all the text nodes directly nested in an element.
This commit is contained in:
Yorick Peterse 2014-08-15 10:07:49 +02:00
parent d0092b434d
commit 24bc84e15e
2 changed files with 38 additions and 2 deletions

View File

@ -103,13 +103,29 @@ module Oga
def inner_text def inner_text
text = '' text = ''
children.each do |child| text_nodes.each do |node|
text << child.text if child.is_a?(Text) text << node.text
end end
return text return text
end end
##
# Returns any {Oga::XML::Text} nodes that are a direct child of this
# element.
#
# @return [Oga::XML::NodeSet]
#
def text_nodes
nodes = NodeSet.new
children.each do |child|
nodes << child if child.is_a?(Text)
end
return nodes
end
## ##
# Converts the element and its child elements to XML. # Converts the element and its child elements to XML.
# #

View File

@ -139,6 +139,26 @@ describe Oga::XML::Element do
end end
end end
context '#text_nodes' do
before do
@t1 = Oga::XML::Text.new(:text => 'Foo')
@t2 = Oga::XML::Text.new(:text => 'Bar')
element = described_class.new(:children => [@t1, @t2])
@set = element.text_nodes
end
it_behaves_like :node_set, :length => 2
example 'return the first Text node' do
@set[0].should == @t1
end
example 'return the second Text node' do
@set[1].should == @t2
end
end
context '#to_xml' do context '#to_xml' do
example 'generate the corresponding XML' do example 'generate the corresponding XML' do
described_class.new(:name => 'p').to_xml.should == '<p></p>' described_class.new(:name => 'p').to_xml.should == '<p></p>'