I have a trouble building a tree structure from materialized path using ruby.
Assuming I have a sorted result set (from couchdb):
[
{ :key => [], :value => "Home" },
{ :key => ["about"], :value => "About" },
{ :key => ["services"], :value => "Services" },
{ :key => ["services", "plans"], :value => "Plans" },
{ :key => ["services", "training"], :value => "Training" },
{ :key => ["services", "training", "python"], :value => "Python" },
{ :key => ["services", "training", "ruby"], :value => "Ruby" }
]
I just need this as a tree in ruby,the following hash is good enough:
{ :title => "Home", :path => [], :children => [
{ :title => "About", :path => ["about"] },
{ :title => "Services", :path => ["services"], :children => [
{ :title => "Plans", :path => ["services", "plans"] }
]}
]}
Could anyone help me?
A simple helper class and a bit of recursion is all you need:
And then:
would give this in
h
:You can sort out the empty
:children
if they matter.