Forked from lancejpollard/awesome_nested_set_optimization_helper.rb
Created
September 5, 2010 01:25
-
-
Save matenia/565652 to your computer and use it in GitHub Desktop.
Converts awesome_nested_set model into a flat array (one sql query!)
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