Skip to content

Commit

Permalink
teach #move_to_child_with_index to accept :root as a target.
Browse files Browse the repository at this point in the history
  • Loading branch information
botandrose-machine committed Feb 28, 2024
1 parent 70cdc5e commit 292969f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
12 changes: 11 additions & 1 deletion lib/awesome_nested_set/model/movable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,17 @@ def move_to_child_of(node)

# Move the node to the child of another node with specify index
def move_to_child_with_index(node, index)
if node.children.empty?
if node == :root
move_to_root
my_position = self_and_siblings.index(self)
if my_position < index
move_to_right_of(self_and_siblings[index])
elsif my_position && my_position == index
# do nothing. already there.
else
move_to_left_of(self_and_siblings[index])
end
elsif node.children.empty?
move_to_child_of(node)
elsif node.children.count == index
move_to_right_of(node.children.last)
Expand Down
7 changes: 7 additions & 0 deletions spec/awesome_nested_set_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -562,6 +562,13 @@
expect(categories(:child_1).left).to eq(2)
expect(categories(:child_1).right).to eq(3)
end

it "move to top level with specified index" do
categories(:child_1).move_to_child_with_index(:root, 1)
expect(categories(:child_1).parent_id).to be_nil
expect(categories(:child_1).left).to eq(9)
expect(categories(:child_1).right).to eq(10)
end
end

it "move_to_child_of_appends_to_end" do
Expand Down

0 comments on commit 292969f

Please sign in to comment.