Created
July 2, 2010 01:39
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inside each suggestion: