Ruby:acts_as_tree嵌套哈希(哈希数组)

时间:2009-09-04 17:56:44

标签: ruby-on-rails ruby

我试图找出一种优雅的方法来“绘制”出一个使用acts_as_tree定义的任意树结构。我的最终目标是将父/子关系转换为可以转换为Yaml文件的嵌套哈希。

示例树:

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

我希望它能产生这个:

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

也许这不是最好的方法?你能为我提供一种转换树的替代方法,所以它或多或少像上面的文字,但是作为Yaml?

2 个答案:

答案 0 :(得分: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: 

怎么样?

答案 1 :(得分:0)

我不知道我是否正确理解了您的问题,但如果您正在寻找生成(yaml)输出树的算法,您可能需要查看at this question(它也是相关的awesome_nested_set但我认为应该可以修改它以便使用acts_as_tree)。

相关问题