Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save matenia/565652 to your computer and use it in GitHub Desktop.
Save matenia/565652 to your computer and use it in GitHub Desktop.
Converts awesome_nested_set model into a flat array (one sql query!)
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