views:

404

answers:

2

I am trying to figure out a graceful way to "draw" out an arbitrary tree structure, defined using acts_as_tree. My ultimate goal is to convert the parent/child relationships into a nested hash that can be converted into a Yaml file.

example tree:

root
--child
--child
----subchild
----subchild
------anotherchld
--child
--child
----subchild
------anotherhchild
--child

I would like it to produce this:

{'root' => 
  [{'child' => nil },
   {'child' => 
     [{'subchild' => nil },
     {'subchild' => nil }]},
...
]}

Perhaps this is not the best approach? Can you provide me an alternate approach for converting the tree so it is more or less like the text above, but as Yaml?

A: 

I don't know if I understood your question correctly, but if you are looking for an algorithm to generate the (yaml) output tree you may want to look at this question (it's related too awesome_nested_set but I think it should be possible to modify it in order to work with acts_as_tree).

Christoph Schiessl
+1  A: 

Ah, recursion:

require 'yaml'

class Category (or whatever)
  def to_hash
    {@name => @children.empty? ? nil : @children.map {|child| child.to_hash}}
  end
end

puts root.to_hash.inspect
puts
puts root.to_hash.to_yaml

Which gives me:

{"root"=>[
  {"child 1"=>nil},
  {"child 2"=>[
    {"subchild 1"=>nil},
    {"subchild 2"=>[
      {"subsubchild 1"=>nil}
    ]}
  ]},
  {"child 3"=>nil},
  {"child 4"=>[
    {"subchild 3"=>[
      {"subsubchild 2"=>nil}
    ]}
  ]},
  {"child 5"=>nil}
]}

root: 
- child 1: 
- child 2: 
  - subchild 1: 
  - subchild 2: 
    - subsubchild 1: 
- child 3: 
- child 4: 
  - subchild 3: 
    - subsubchild 2: 
- child 5:

How's that?

glenn mcdonald