Skip to content

Commit

Permalink
Merge pull request #23 from MichalPokorny/leaves-scope
Browse files Browse the repository at this point in the history
Add leaves scope
  • Loading branch information
amerine committed Apr 21, 2014
2 parents c299067 + 74f0102 commit 1f58259
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
24 changes: 22 additions & 2 deletions lib/acts_as_tree.rb
Original file line number Diff line number Diff line change
Expand Up @@ -94,15 +94,35 @@ def acts_as_tree(options = {})
after_update :update_parents_counter_cache
def self.roots
def self.default_tree_order
order_option = %Q{#{configuration.fetch :order, "nil"}}
where(:#{configuration[:foreign_key]} => nil).order(order_option)
order(order_option)
end
def self.root
self.roots.first
end
def self.roots
where(:#{configuration[:foreign_key]} => nil).default_tree_order
end
EOV

if configuration[:counter_cache]
class_eval <<-EOV
def self.leaves
where(:children_count => 0).default_tree_order
end
EOV
else
# Fallback to less efficent ways to find leaves.
class_eval <<-EOV
def self.leaves
internal_ids = select(:#{configuration[:foreign_key]}).where(arel_table[:#{configuration[:foreign_key]}].not_eq(nil))
where("id NOT IN (\#{internal_ids.to_sql})").default_tree_order
end
EOV
end
end

end
Expand Down
12 changes: 12 additions & 0 deletions test/acts_as_tree_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ class TreeTest < MiniTest::Unit::TestCase

def setup
setup_db

@root1 = TreeMixin.create!
@root_child1 = TreeMixin.create! parent_id: @root1.id
@child1_child = TreeMixin.create! parent_id: @root_child1.id
Expand Down Expand Up @@ -139,6 +140,14 @@ def test_roots
assert_equal [@root1, @root2, @root3], TreeMixin.roots
end

def test_leaves
assert_equal [@child1_child_child, @root_child2, @root2, @root3], TreeMixin.leaves
end

def test_default_tree_order
assert_equal [@root1, @root_child1, @child1_child, @child1_child_child, @root_child2, @root2, @root3], TreeMixin.default_tree_order
end

def test_siblings
assert_equal [@root2, @root3], @root1.siblings
assert_equal [@root_child2], @root_child1.siblings
Expand Down Expand Up @@ -408,4 +417,7 @@ def test_update_parents_counter_cache
assert_equal 0, @child1.reload.children_count
end

def test_leaves
assert_equal [@child1_child1, @child2], TreeMixinWithCounterCache.leaves
end
end

0 comments on commit 1f58259

Please sign in to comment.