From b594e99ac00184fcb54c6b70c92f089fbac9150c Mon Sep 17 00:00:00 2001 From: James Brown Date: Tue, 11 Jun 2024 16:08:31 -0700 Subject: [PATCH] add in_subtree_of? helper function, for symmetry --- README.md | 2 +- lib/ancestry/instance_methods.rb | 4 ++++ test/concerns/tree_predicate_test.rb | 4 ++++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1546cfa0..68ccb928 100644 --- a/README.md +++ b/README.md @@ -151,7 +151,7 @@ The yellow nodes are those returned by the method. | includes self |self..indirects |root..self | |`sibling_ids` |`subtree_ids` |`path_ids` | |`has_siblings?` | | | -|`sibling_of?(node)` | | | +|`sibling_of?(node)` |`in_subtree_of?` | | When using `STI` all classes are returned from the scopes unless you specify otherwise using `where(:type => "ChildClass")`. diff --git a/lib/ancestry/instance_methods.rb b/lib/ancestry/instance_methods.rb index 331446ea..8d898093 100644 --- a/lib/ancestry/instance_methods.rb +++ b/lib/ancestry/instance_methods.rb @@ -303,6 +303,10 @@ def subtree_ids depth_options = {} subtree(depth_options).pluck(self.class.primary_key) end + def in_subtree_of?(node) + id == node.id || descendant_of?(node) + end + # Callback disabling def without_ancestry_callbacks diff --git a/test/concerns/tree_predicate_test.rb b/test/concerns/tree_predicate_test.rb index 4a3eed85..c57d6304 100644 --- a/test/concerns/tree_predicate_test.rb +++ b/test/concerns/tree_predicate_test.rb @@ -31,6 +31,10 @@ def test_tree_predicates # Descendants assertions assert children.map { |n| !root.descendant_of?(n) }.all? assert children.map { |n| n.descendant_of?(root) }.all? + # Subtrees assertions + assert children.map { |n| n.in_subtree_of?(root) }.all? + assert children.map { |n| !root.in_subtree_of?(n) }.all? + assert root.in_subtree_of?(root) end end end