Search code examples
rubyenumerable

Do I need an Enumerator for this?


I want to do this:

<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>

The method render_menu would look something like this:

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

I'm not sure what the render_menu needs to return to get the three params.. The render_menu will grab the default menu items if no argument is given..


Solution

  • You have to use yield and replace each for collect inside 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
    

    You should also modify your template to not display the value returned by render_menu:

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