diff --git a/lib/oga/xml/node.rb b/lib/oga/xml/node.rb index 1ab9fdc..201feb0 100644 --- a/lib/oga/xml/node.rb +++ b/lib/oga/xml/node.rb @@ -152,6 +152,27 @@ module Oga return node_set.delete(self) if node_set end + ## + # Replaces the current node with another. + # + # @example Replacing with an element + # element = Oga::XML::Element.new(:name => 'div') + # some_node.replace(element) + # + # @example Replacing with a String + # some_node.replace('this will replace the current node with a text node') + # + # @param [String|Oga::XML::Node] other + # + def replace(other) + if other.is_a?(String) + other = Text.new(:text => other) + end + + before(other) + remove + end + ## # Inserts the given node before the current node. # diff --git a/spec/oga/xml/node_spec.rb b/spec/oga/xml/node_spec.rb index b52621f..34cb5ba 100644 --- a/spec/oga/xml/node_spec.rb +++ b/spec/oga/xml/node_spec.rb @@ -179,6 +179,28 @@ describe Oga::XML::Node do end end + describe '#replace' do + before do + @node = described_class.new + @container = described_class.new(:children => [@node]) + end + + it 'replaces a node with another node when called with Oga::XML::Node' do + other = described_class.new + + @node.replace(other) + + @container.children[0].should == other + end + + it 'replaces a node with Oga::XML::Text when called with String' do + @node.replace('a string') + + @container.children[0].should be_an_instance_of(Oga::XML::Text) + @container.children[0].text.should == 'a string' + end + end + describe '#before' do before do @node = described_class.new