Skip to content

Instantly share code, notes, and snippets.

@papricek
Created December 25, 2011 08:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save papricek/1518887 to your computer and use it in GitHub Desktop.
Save papricek/1518887 to your computer and use it in GitHub Desktop.
Render tree within a single sql query
def render_tree(nodes = [])
stack = []
html = ""
nodes.each do |node|
if stack.empty?
html << start_tag(node)
stack.push(node)
next
end
if stack.last.lft < node.lft && node.lft < stack.last.rgt
if node.leaf?
html << node_tag(node)
else
html << start_tag(node)
stack.push(node)
end
if node.rgt + 1 == stack.last.rgt
html << end_tag
stack.pop
end
else
html << end_tag
stack.pop
redo
end
end
content_tag(:ul, html.html_safe, :id => "category-tree")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment