Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save lancejpollard/460814 to your computer and use it in GitHub Desktop.
Save lancejpollard/460814 to your computer and use it in GitHub Desktop.
Goal: Convert entire hierarchy of models into tree in 1 database call, such that you can loop through them depth-first
def simple_nested_set(clazz) # Post for example
stack = [] # Post for example
result = []
clazz.all(:order => "lft").each do |node|
if stack.empty?
stack.push({:node => node, :children => []})
result << stack.last
next
end
if stack.last[:node].lft < node.lft && node.lft < stack.last[:node].rgt
child = {:node => node, :children => []}
stack.last[:children] << child
if node.rgt + 1 == stack.last[:node].rgt
stack.pop
end
unless node.leaf? # (node.rgt - node.lft == 1)
stack.push(child)
end
else
stack.pop
end
end
result
end
@sposmen
Copy link

sposmen commented Feb 2, 2023

Inside each suggestion:

      stack.pop while stack.any? && node.lft > stack.last[:node].rgt
      child = {node: node, children: []}
      (stack.empty? ? result : stack.last[:children]) << child
      stack << child

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment