From 24bc84e15e93a9a9c06ecdf4a3654a06a2879909 Mon Sep 17 00:00:00 2001 From: Yorick Peterse Date: Fri, 15 Aug 2014 10:07:49 +0200 Subject: [PATCH] Added XML::Element#text_nodes. This method returns all the text nodes directly nested in an element. --- lib/oga/xml/element.rb | 20 ++++++++++++++++++-- spec/oga/xml/element_spec.rb | 20 ++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/lib/oga/xml/element.rb b/lib/oga/xml/element.rb index 48aae24..70154ca 100644 --- a/lib/oga/xml/element.rb +++ b/lib/oga/xml/element.rb @@ -103,13 +103,29 @@ module Oga def inner_text text = '' - children.each do |child| - text << child.text if child.is_a?(Text) + text_nodes.each do |node| + text << node.text end return text 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. # diff --git a/spec/oga/xml/element_spec.rb b/spec/oga/xml/element_spec.rb index 61793f0..0dfc56a 100644 --- a/spec/oga/xml/element_spec.rb +++ b/spec/oga/xml/element_spec.rb @@ -139,6 +139,26 @@ describe Oga::XML::Element do 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 example 'generate the corresponding XML' do described_class.new(:name => 'p').to_xml.should == '

'