I am looking to display a html tree from nested set data.
As the displayed tree does not always display all branches the leaf nodes cannot be identified by subtracting the lft & rgt values.
1 Drinks 27
/ | \
2 Coffee 3 4 Tea 20 21 Milk 26
/ \
5 Black 8 9 Green 19
/ \
10 China 14 15 Africa 18
I was looking to adapt the following code: How to render all records from a nested set into a real html tree
Solution:
Happy to receive code improvement suggestions :)
def tree_from_set(set, start_level)
buf = "<ul>"
parent = []
prev = set[start_level]
set[start_level+1..-1].each do |node|
if node.lft.between?(prev.lft, prev.rgt)
# Previous was the parent
buf << open_parent_tag(prev)
parent.push(prev)
else
if node.lft.between?(parent.last.lft, parent.last.rgt)
#Previous was a child
buf << leaf_tag(prev)
else
buf << leaf_tag(prev)
begin
buf << "</ul></li>"
parent.pop
end until parent.empty? or node.lft.between?(parent.last.lft, parent.last.rgt)
end
end
prev = node
end
buf << leaf_tag(prev)
begin
buf << "</ul></li>"
parent.pop
end until parent.empty?
buf << "</ul>"
buf.html_safe
end
def open_parent_tag(node)
%{ <li>
#{link_to(node.name, node)}
<ul>
}
end
def leaf_tag(node)
content_tag(:li, link_to(node.name, node))
end
I used this function, but on php, not on ruby: