2009-09-04 165 views
1

我想找出一个优雅的方式来“绘制”出一个任意的树结构,使用acts_as_tree定义。我的最终目标是将父/子关系转换为可以转换为Yaml文件的嵌套哈希。ruby​​:acts_as_tree嵌套散列(散列数组)

例如树:

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

我想它产生这样的:

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

也许这是不是最好的方法?你能否为我提供一种替代方法来转换树,因此它与上面的文本差不多,但是作为Yaml?

回答

0

我不知道如果我理解正确你的问题,但如果你正在寻找一个算法来生成(YAML)输出树,你可能想看看at this question(它的相关过于awesome_nested_set但我认为它应该是可能的修改它以便与acts_as_tree一起使用)。

1

啊,递归:

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 

这给了我:

{"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: 

是如何形成的?