我需要一个枚举器吗?

时间:2013-04-05 14:40:27

标签: ruby enumerable

我想这样做:

<div class="menu">

  <%- render_menu do |title,path,children| %>

    <%= link_to title, path %>

    <div class="submenu">
      <%= render_menu(children) do |title,path,children| %>
        <%= link_to title, path %>
        <%= children %>
      <%- end %>
    </div>

  <% end %>

</div>

方法render_menu看起来像这样:

def render_menu(children=nil)
  children = Paths.roots if children.nil?
  children.collect do |child|
    [ child.title, child.path, child.children ]
  end
end

我不确定render_menu需要返回以获得三个参数... 如果没有给出参数,render_menu将获取默认菜单项。

1 个答案:

答案 0 :(得分:0)

您必须使用yield并将each替换为collect内的render_menu

def render_menu(children=nil)
  children = Paths.roots if children.nil?
  children.each do |child|
    yield([child.title, child.path, child.children])
  end
end

您还应修改模板,以便不显示render_menu返回的值:

<div class="submenu">
    <% render_menu(children) do |title,path,children| %>
        <%= link_to title, path %>
        <%= children %>
    <% end %>
</div>