Skip to content

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also compare across forks.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also compare across forks.
...
Checking mergeability… Don’t worry, you can still create the pull request.
  • 8 commits
  • 2 files changed
  • 0 commit comments
  • 1 contributor
Showing with 48 additions and 0 deletions.
  1. +22 −0 lib/awesome_nested_set/awesome_nested_set.rb
  2. +26 −0 spec/awesome_nested_set_spec.rb
View
22 lib/awesome_nested_set/awesome_nested_set.rb
@@ -439,6 +439,28 @@ def move_to_root
move_to nil, :root
end
+ # Order children in a nested set by an attribute
+ # Can order by any attribute class that uses the Comparable mixin, for example a string or integer
+ # Usage example when sorting categories alphabetically: @new_category.move_to_ordered_child_of(@root, "name")
+ def move_to_ordered_child_of(parent, order_attribute, ascending = true)
+ self.move_to_root and return unless parent
+ left = nil # This is needed, at least for the tests.
+ parent.children.each do |n| # Find the node immediately to the left of this node.
+ if ascending
+ left = n if n.send(order_attribute) < self.send(order_attribute)
+ else
+ left = n if n.send(order_attribute) > self.send(order_attribute)
+ end
+ end
+ self.move_to_child_of(parent)
+ return unless parent.children.count > 1 # Only need to order if there are multiple children.
+ if left # Self has a left neighbor.
+ self.move_to_right_of(left)
+ else # Self is the left most node.
+ self.move_to_left_of(parent.children[0])
+ end
+ end
+
def move_possible?(target)
self != target && # Can't target self
same_scope?(target) && # can't be in different scopes
View
26 spec/awesome_nested_set_spec.rb
@@ -565,6 +565,32 @@
Category.roots.last.to_text.should == output
end
+ it "should_move_to_ordered_child" do
+ node1 = Category.create(:name => 'Node-1')
+ node2 = Category.create(:name => 'Node-2')
+ node3 = Category.create(:name => 'Node-3')
+
+ node2.move_to_ordered_child_of(node1, "name")
+
+ assert_equal node1, node2.parent
+ assert_equal 1, node1.children.count
+
+ node3.move_to_ordered_child_of(node1, "name", true) # acending
+
+ assert_equal node1, node3.parent
+ assert_equal 2, node1.children.count
+ assert_equal node2.name, node1.children[0].name
+ assert_equal node3.name, node1.children[1].name
+
+ node3.move_to_ordered_child_of(node1, "name", false) # decending
+ node1.reload
+
+ assert_equal node1, node3.parent
+ assert_equal 2, node1.children.count
+ assert_equal node3.name, node1.children[0].name
+ assert_equal node2.name, node1.children[1].name
+ end
+
it "valid_with_null_lefts" do
Category.valid?.should be_true
Category.update_all('lft = null')

No commit comments for this range

Something went wrong with that request. Please try again.