0

我有一个Skill模型,它有很多先决条件(或prereqs在我的模型中),我需要为技能创建一个 N 级深度的先决条件图,因为我需要将此信息传递给 Javascript(在我的 gon gem 中)控制器)用于一些疯狂的 HTML5/KineticJS 动作,显示此技能与其他技能之间关系的鸟瞰图。

现在,下面的代码可以很好地一致地映射 5 个级别的深度。

delegate :url_helpers, to: 'Rails.application.routes'

def prereqs_map
  prereqs_array = [ self.title.to_s, url_helpers.skill_path(self), Array.new(prereqs) ]
  prereqs_array[2] = prereqs_array[2].map do |prereq1|
    prereq1 = [ prereq1.title.to_s, url_helpers.skill_path(prereq1), Array.new(prereq1.prereqs).map do |prereq2|
      prereq2 = [ prereq2.title.to_s, url_helpers.skill_path(prereq2), Array.new(prereq2.prereqs).map do |prereq3|
        prereq3 = [ prereq3.title.to_s, url_helpers.skill_path(prereq3), Array.new(prereq3.prereqs).map do |prereq4|
          prereq4 = [ prereq4.title.to_s, url_helpers.skill_path(prereq4), Array.new(prereq4.prereqs).map do |prereq5|
            prereq5 = [ prereq5.title.to_s, url_helpers.skill_path(prereq5), [] ]
          end ] # prereq depth 5
        end ] # prereq depth 4
      end ] # prereq depth 3
    end ] # prereq depth 2
  end   # prereq depth 1

  return prereqs_array
end

如您所见,问题在于嵌套映射非常混乱,我无法弄清楚传递depth参数并将方法映射到我传递的任何深度。

我认为必须有更好的方法来做到这一点。有什么想法吗?

4

2 回答 2

2

试试这个:

class Skill
  # has many prereqs?

  def prereqs_map(depth = 5)
    mapping = Proc.new do |node, depth, current_level|
      [node.title.to_s, url_helpers.skill_path(node), node.prereqs.map {|prereq| mapping.call(prereq, depth, current_level+1)}] if current_level <= depth
    end
    mapping.call(self, depth, 0)
  end

end

>> skill.prereqs_map(5)
于 2012-12-30T18:00:50.920 回答
1

通过向模型添加实例方法“to_tree”,您可以对其进行递归。下面随机设置一个依赖树,然后为您提供所需格式的数组数组。

class Skill

  attr_accessor :prereqs
  attr_accessor :title

  def randomly_create_tree depth=0
    self.title = ["Coding", "Winning", "Smiling", "Eating"][rand(4)]
    if depth < 3
      self.prereqs = []
      (0..rand(3)).each do
        skill = Skill.new
        skill.randomly_create_tree(depth + 1)
        self.prereqs << skill
      end
    else
      self.prereqs = []
    end
    self
  end

  def to_tree
    prereqs.collect do |prereq|
      [self.title, prereq.to_tree]
    end
  end

进而:

s = Skill.new
s.randomly_create_tree
s.to_tree

结果是:

[["Coding", [["Winning", [["Winning", []], ["Winning", []]]]]]] 

其中每个字符串都是随机生成的标题。您可能还想添加您的 url_helpers.skill_path ,但我不确定那是什么。

于 2012-12-30T17:56:30.007 回答