Skip to content

Commit 95f1372

Browse files
committed
Guard rename_child collisions
Raise when renaming a child to an existing sibling name to prevent overwriting entries in the children hash. This avoids orphaning nodes and keeps child lookup consistent.
1 parent e0677e7 commit 95f1372

2 files changed

Lines changed: 6 additions & 0 deletions

File tree

lib/tree.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -457,6 +457,9 @@ def rename_child(old_name, new_name)
457457
raise ArgumentError, "Invalid child name specified: #{old_name}"\
458458
unless @children_hash.key?(old_name)
459459

460+
raise ArgumentError, "Child name already exists: #{new_name}"\
461+
if @children_hash.key?(new_name)
462+
460463
@children_hash[new_name] = @children_hash.delete(old_name)
461464
@children_hash[new_name].name = new_name
462465
end

test/test_tree.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1545,6 +1545,9 @@ def test_rename_child
15451545

15461546
assert_raise(ArgumentError) { @root.rename_child('Not_Present_Child1', 'ALT_Child1') }
15471547

1548+
error = assert_raise(ArgumentError) { @root.rename_child('Child1', 'Child2') }
1549+
assert_match(/Child name already exists: Child2/, error.message)
1550+
15481551
@root.rename_child('Child1', 'ALT_Child1')
15491552
assert_equal('ALT_Child1', @child1.name, "Name should be 'ALT_Child1'")
15501553
assert_equal(@child1, @root['ALT_Child1'], 'Should be able to access from parent using new name')

0 commit comments

Comments
 (0)