Ability to replace a node with another node or string

```
element = Oga::XML::Element.new(:name => 'div')
some_node.replace(element)
```

You can also pass a `String` to  `replace` and it will be replaced with
a `Oga::XML::Text` node

```
some_node.replace('this will replace the current node with a text node')
```

closes #115
This commit is contained in:
Tero Tasanen 2015-06-17 09:32:58 +03:00
parent fe7e2e4f74
commit 0b4791b277
2 changed files with 43 additions and 0 deletions

View File

@ -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.
#

View File

@ -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