1

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?

2 Answers 2

1

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?

Sign up to request clarification or add additional context in comments.

Comments

0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.