From 94965961cea1b1cf2dd0ffce0788b5ba54c06c96 Mon Sep 17 00:00:00 2001 From: Yorick Peterse Date: Fri, 4 Jul 2014 09:50:05 +0200 Subject: [PATCH] Added XML::Element#inner_text. This method can be used to retrieve the text of the given node only. In other words, unlike Element#text it does not contain the text of any child nodes. --- lib/oga/xml/element.rb | 15 +++++++++++++++ spec/oga/xml/element_spec.rb | 18 ++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/lib/oga/xml/element.rb b/lib/oga/xml/element.rb index aaf9af9..cbe8966 100644 --- a/lib/oga/xml/element.rb +++ b/lib/oga/xml/element.rb @@ -55,6 +55,21 @@ module Oga return children.text end + ## + # Returns the text of the current element only. + # + # @return [String] + # + def inner_text + text = '' + + children.each do |child| + text << child.text if child.is_a?(Text) + end + + return text + 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 b6d60f0..5f34a94 100644 --- a/spec/oga/xml/element_spec.rb +++ b/spec/oga/xml/element_spec.rb @@ -46,6 +46,24 @@ describe Oga::XML::Element do end end + context '#inner_text' do + before do + t1 = Oga::XML::Text.new(:text => 'Foo') + t2 = Oga::XML::Text.new(:text => 'Bar') + + @n1 = described_class.new(:children => [t1]) + @n2 = described_class.new(:children => [@n1, t2]) + end + + example 'return the inner text of the parent node' do + @n2.inner_text.should == 'Bar' + end + + example 'return the inner text of the child node' do + @n1.inner_text.should == 'Foo' + end + end + context '#to_xml' do example 'generate the corresponding XML' do described_class.new(:name => 'p').to_xml.should == '

'