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 an instance method to check the relationship between 2 nodes: #family_of? #319

Merged
merged 1 commit into from
Aug 27, 2018
Merged
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,7 @@ When you include ```has_closure_tree``` in your model, you can provide a hash to
* ```tag.descendant_of?(node)``` returns true if current node is descendant of another one
* ```tag.self_and_descendants``` returns a scope of self, all children, childrens' children, etc., ordered by depth.
* ```tag.self_and_descendant_ids``` returns IDs of self, all children, childrens' children, etc., ordered by depth.
* ```tag.family_of?``` returns true if current node and another one have a same root.
* ```tag.hash_tree``` returns an [ordered, nested hash](#nested-hashes) that can be depth-limited.
* ```tag.find_by_path(path)``` returns the node whose name path *from ```tag```* is ```path```. See (#find_or_create_by_path).
* ```tag.find_or_create_by_path(path)``` returns the node whose name path *from ```tag```* is ```path```, and will create the node if it doesn't exist already.See (#find_or_create_by_path).
Expand Down
5 changes: 5 additions & 0 deletions lib/closure_tree/model.rb
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,11 @@ def child_of?(node)
self.parent == node
end

# node and record have a same root
def family_of?(node)
self.root == node.root
end

# Alias for appending to the children collection.
# You can also add directly to the children collection, if you'd prefer.
def add_child(child_node)
Expand Down
8 changes: 8 additions & 0 deletions spec/label_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -633,6 +633,14 @@ def roots_name_and_order
expect(@d2.descendant_of?(@a1)).to be_truthy
expect(@b1.descendant_of?(@a2)).to be_falsey
end

it "checks descendant of node" do
expect(@b1.family_of?(@b1)).to be_truthy
expect(@a1.family_of?(@c1)).to be_truthy
expect(@d3.family_of?(@a2)).to be_truthy
expect(@c1.family_of?(@d2)).to be_truthy
expect(@c3.family_of?(@a1)).to be_falsey
end
end

end