From 6cb2d548758f1ade6f363dbeda14807d400fd680 Mon Sep 17 00:00:00 2001 From: Yorick Peterse Date: Wed, 10 Sep 2014 23:25:39 +0200 Subject: [PATCH] Added XML::Element#inner_text= This method can be used to more easily set the text of an element, without having to manually muck around with XML::Text instances. --- lib/oga/xml/element.rb | 13 +++++++++++++ spec/oga/xml/element_spec.rb | 18 ++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/lib/oga/xml/element.rb b/lib/oga/xml/element.rb index 13cdb50..f4aebec 100644 --- a/lib/oga/xml/element.rb +++ b/lib/oga/xml/element.rb @@ -145,6 +145,19 @@ module Oga return nodes end + ## + # Sets the inner text of the current element to the given String. + # + # @param [String] text + # + def inner_text=(text) + children.each do |child| + child.remove if child.is_a?(Text) + end + + children << XML::Text.new(:text => 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 764e710..ae46c48 100644 --- a/spec/oga/xml/element_spec.rb +++ b/spec/oga/xml/element_spec.rb @@ -151,6 +151,24 @@ describe Oga::XML::Element do end end + context '#inner_text=' do + before do + @element = described_class.new + end + + example 'set the inner text of an element' do + @element.inner_text = 'foo' + @element.inner_text.should == 'foo' + end + + example 'remove existing text nodes before inserting new nodes' do + @element.children << Oga::XML::Text.new(:text => 'foo') + + @element.inner_text = 'bar' + @element.inner_text.should == 'bar' + end + end + context '#text_nodes' do before do @t1 = Oga::XML::Text.new(:text => 'Foo')