Skip to content

Instantly share code, notes, and snippets.

@meltingice
Created May 23, 2017 21:38
Show Gist options
  • Save meltingice/3daffee58e8e3ddd2a3414010c267bda to your computer and use it in GitHub Desktop.
Save meltingice/3daffee58e8e3ddd2a3414010c267bda to your computer and use it in GitHub Desktop.
node_index.each do |node_id, data|
# This is a root node, no processing to do.
next if data[:node].ancestry.nil?
# Here we check the nesting depth to make sure it is not over the max
# allowed depth.
assigned_parent_id = nil
if data[:node].depth > Comment::MAX_DEPTH
# Comment is nested deeper than the max allowed depth, which means we
# convert it to a "reply to" style comment and move it up the tree to
# the max depth.
#
# We explicitly use ancestor_ids here because it does not generate a
# database query.
assigned_parent_id = data[:node].ancestor_ids[Comment::MAX_DEPTH - 1]
# Since we have that handy index of comments, we can easily reference the
# comment that this one is a reply to.
data[:reply_to] = node_index[data[:node].parent_id][:node]
else
# If we're not over the max nesting depth, we can just proceed as usual.
assigned_parent_id = data[:node].parent_id
end
# We store a reference to the parent comment ID for later use
data[:parent] = assigned_parent_id
# And finally, we add this comment to the parent comments children. This is
# where the structure of the tree starts to take form.
node_index[assigned_parent_id][:children].unshift data
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment