从物化路径构建树

时间:2011-10-17 15:03:21

标签: ruby tree couchdb materialized-path-pattern

使用ruby从物化路径构建树结构时遇到问题。

假设我有一个排序结果集(来自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" }
]

我只需要将它作为ruby中的树,以下哈希就足够了:

{ :title => "Home", :path => [], :children => [
  { :title => "About", :path => ["about"] }, 
  { :title => "Services", :path => ["services"], :children => [
    { :title => "Plans", :path => ["services", "plans"] }
  ]}
]}

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:4)

您需要一个简单的帮助程序类和一点递归:

class Tree
  attr_reader :root

  def initialize
    @root = { :title => 'Home', :path => [ ], :children => [ ] }
  end

  def add(p)
    r_add(@root, p[:key].dup, p[:value])
    self
  end

private

  def r_add(h, path, value)
    if(path.empty?)
      h[:title] = value 
      return
    end

    p = path.shift
    c = h[:children].find { |c| c[:path].last == p } 
    if(!c)
      c = { :title => nil, :path => h[:path].dup.push(p), :children => [ ] }
      h[:children].push(c)
    end
    r_add(c, path, value)
  end

end

然后:

t = a.inject(Tree.new) { |t, h| t.add(h) }
h = t.root

会在h中提供此内容:

{:title =>"Home", :path=>[], :children=>[
  {:title=>"About", :path=>["about"], :children=>[]},
  {:title=>"Services", :path=>["services"], :children=>[
    {:title=>"Plans", :path=>["services", "plans"], :children=>[]},
    {:title=>"Training", :path=>["services", "training"], :children=>[
      {:title=>"Python", :path=>["services", "training", "python"], :children=>[]}, 
      {:title=>"Ruby", :path=>["services", "training", "ruby"], :children=>[]}
    ]}
  ]}
]}

如果重要,可以整理空:children