Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add leaves instance method #341

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions lib/ancestry/instance_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,12 @@ def subtree_ids depth_options = {}
subtree(depth_options).pluck(self.ancestry_base_class.primary_key)
end

# Leaves

def leaves
subtree.select{|node| node.childless? }
end

# Callback disabling

def without_ancestry_callbacks
Expand Down
12 changes: 12 additions & 0 deletions test/concerns/tree_navigration_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ def test_tree_navigation
assert_equal descendants.map(&:id), lvl0_node.descendant_ids
assert_equal descendants, lvl0_node.descendants
assert_equal [lvl0_node] + descendants, lvl0_node.subtree
# Leaves assertions
leaves = lvl0_node.descendants.select do |node|
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ideas how to test this without just rewriting the implementation here?

node.childless?
end
assert_equal lvl0_node.leaves, leaves

lvl0_children.each do |lvl1_node, lvl1_children|
# Ancestors assertions
Expand Down Expand Up @@ -68,6 +73,11 @@ def test_tree_navigation
assert_equal descendants.map(&:id), lvl1_node.descendant_ids
assert_equal descendants, lvl1_node.descendants
assert_equal [lvl1_node] + descendants, lvl1_node.subtree
# Leaves assertions
leaves = lvl1_node.descendants.select do |node|
node.childless?
end
assert_equal lvl1_node.leaves, leaves

lvl1_children.each do |lvl2_node, lvl2_children|
# Ancestors assertions
Expand Down Expand Up @@ -101,6 +111,8 @@ def test_tree_navigation
assert_equal descendants.map(&:id), lvl2_node.descendant_ids
assert_equal descendants, lvl2_node.descendants
assert_equal [lvl2_node] + descendants, lvl2_node.subtree
# Leaves assertions
assert_equal lvl2_node.leaves, [lvl2_node]
end
end
end
Expand Down