From c701fbe350028aae5a2fbf34abc6584bf7b954ff Mon Sep 17 00:00:00 2001 From: Aaron Lasseigne Date: Sun, 27 Jun 2010 17:54:01 -0500 Subject: [PATCH] adding Manipulate::swap --- CHANGELOG.rdoc | 2 +- lib/rind/manipulate.rb | 27 +++++++++++++++++++++++++++ test/manipulate_test.rb | 10 ++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.rdoc b/CHANGELOG.rdoc index b0cf27d..160b717 100755 --- a/CHANGELOG.rdoc +++ b/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'. diff --git a/lib/rind/manipulate.rb b/lib/rind/manipulate.rb index 84c9acf..6a14207 100755 --- a/lib/rind/manipulate.rb +++ b/lib/rind/manipulate.rb @@ -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 self from one node set with a node 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 diff --git a/test/manipulate_test.rb b/test/manipulate_test.rb index 77339dc..8cbe311 100755 --- a/test/manipulate_test.rb +++ b/test/manipulate_test.rb @@ -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