Skip to content

Commit

Permalink
Add an instance method to check the relationship between 2 nodes
Browse files Browse the repository at this point in the history
  • Loading branch information
rnitta committed Jul 27, 2018
1 parent 5d44d22 commit c1beee5
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 0 deletions.
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

0 comments on commit c1beee5

Please sign in to comment.