Skip to content
This repository has been archived by the owner on Jun 26, 2022. It is now read-only.

Commit

Permalink
adding Manipulate::swap
Browse files Browse the repository at this point in the history
  • Loading branch information
AaronLasseigne committed Jun 27, 2010
1 parent 55173d3 commit c701fbe
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
2 changes: 1 addition & 1 deletion CHANGELOG.rdoc
@@ -1,6 +1,6 @@
== 0.2.0
* Optimized traversal functions for better performance.
* Adding Node::is_root?, Node::is_leaf? and Manipulate::replace functions.
* Adding Node::is_root?, Node::is_leaf?, Manipulate::replace and Manipulate::swap functions.

== 0.1.5 - 2010.06.27
* Xpath query parser was not matching leading '//axis::node' correctly. The axis was being parsed as '/axis'.
Expand Down
27 changes: 27 additions & 0 deletions lib/rind/manipulate.rb
Expand Up @@ -33,8 +33,35 @@ def remove
# nodes[1].replace('y', 'z') => ['a', 'y', 'z', 'c']
def replace(*nodes)
children = self.parent.children

index = children.exact_index(self)
children.delete_at(index)

children.insert(index, *nodes)
end

# Swap <tt>self</tt> from one node set with a <tt>node</tt> from another node set.
# === Example
# nodes = ['a', 'b', 'c']
# nodes[1].swap('d') => ['a', 'd', 'c']
#
# abc = ['a', 'b', 'c']
# xyz = ['x', 'y', 'z']
# abc[1].swap(xyz[1]) => ['a', 'y', 'c']
# xyz => ['x', 'b', 'z']
def swap(node)
self_children = self.parent.children
node_children = node.parent.children

self_index = self_children.exact_index(self)
node_index = node_children.exact_index(node)

self_children.delete_at(self_index)
node_children.delete_at(node_index)

self_children.insert(self_index, node)
node_children.insert(node_index, self)

self_children
end
end
10 changes: 10 additions & 0 deletions test/manipulate_test.rb
Expand Up @@ -29,4 +29,14 @@ def test_replace

assert_equal(@a.children[0].replace(c1, c2), [c1, c2, @b2, @b3])
end

def test_swap
z = Rind::Html::Z.new()
y1 = Rind::Html::Y.new()
y2 = Rind::Html::Y.new()
z.children.push(y1, y2)

assert_equal(@a.children[1].swap(y2), [@b1, y2, @b3])
assert_equal(z.children, [y1, @b2])
end
end

0 comments on commit c701fbe

Please sign in to comment.