Skip to content

Commit b19ee94

Browse files
committed
Prevent adding ancestor as child
1 parent 9ee7517 commit b19ee94

2 files changed

Lines changed: 8 additions & 0 deletions

File tree

lib/tree.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,10 @@ def add(child, at_index = -1)
394394

395395
raise ArgumentError, 'Attempting add root as a child' if child.equal?(root)
396396

397+
if (ancestors = parentage) && ancestors.include?(child)
398+
raise ArgumentError, 'Attempting add ancestor as a child'
399+
end
400+
397401
# Lazy man's unique test, won't test if children of child are unique in
398402
# this tree too.
399403
raise "Child #{child.name} already added!"\

test/test_tree.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -491,6 +491,10 @@ def test_add
491491

492492
# Test the addition of a nil node.
493493
assert_raise(ArgumentError) { @root.add(nil) }
494+
495+
# Test adding an ancestor as a child (cycle prevention).
496+
error = assert_raise(ArgumentError) { @child4.add(@child3) }
497+
assert_match(/Attempting add ancestor as a child/, error.message)
494498
end
495499

496500
# Test the addition of a duplicate node (duplicate being defined as a node with the same name).

0 commit comments

Comments
 (0)