Created
December 25, 2011 08:33
-
-
Save papricek/1518887 to your computer and use it in GitHub Desktop.
Render tree within a single 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 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