Skip to content

Commit f669740

Browse files
committed
Add option on how to handle orphans when arranging nodes
1 parent 9dab81f commit f669740

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

lib/ancestry/class_methods.rb

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,16 +38,27 @@ def arrange options = {}
3838
# arranges array of nodes to a hierarchical hash
3939
#
4040
# @param nodes [Array[Node]] nodes to be arranged
41+
# @param orphan_strategy [Symbol] :rootify or :destroy (default: :rootify)
4142
# @returns Hash{Node => {Node => {}, Node => {}}}
4243
# If a node's parent is not included, the node will be included as if it is a top level node
43-
def arrange_nodes(nodes)
44+
def arrange_nodes(nodes, orphan_strategy: :rootify)
4445
node_ids = Set.new(nodes.map(&:id))
4546
index = Hash.new { |h, k| h[k] = {} }
4647

4748
nodes.each_with_object({}) do |node, arranged|
48-
children = index[node.id]
49-
index[node.parent_id][node] = children
50-
arranged[node] = children unless node_ids.include?(node.parent_id)
49+
index[node.parent_id][node] = children = index[node.id]
50+
if node.parent_id.nil?
51+
arranged[node] = children
52+
elsif !node_ids.include?(node.parent_id)
53+
case orphan_strategy
54+
# when :destroy # All children are destroyed as well (default)
55+
# when :adopt then raise ArgumentError, "Not Implemented"
56+
when :rootify
57+
arranged[node] = children
58+
when :restrict
59+
raise Ancestry::AncestryException.new(I18n.t("ancestry.cannot_delete_descendants"))
60+
end
61+
end
5162
end
5263
end
5364

0 commit comments

Comments
 (0)