I have categories and subcategories in my view. The code looks like this
<ul>
<% Category.roots.each do |category| %>
<li class="col-md-2">
<a href="#"><%= category.name %></a>
<% if !category.children.empty? %>
<ul>
<%= category.decorate.draw_tree %>
</ul>
<% end %>
</li>
<% end %>
</ul>
I'm basically using a decorator
to make it recursive
class CategoryDecorator < Draper::Decorator
delegate_all
decorates :category
def draw_tree
children.inject("") do |memo, child|
memo << "<li class=\"dir\"><a href=\"#\">#{child.name}</a>"
memo << "<ul>#{child.decorate.draw_tree}</ul>" if not child.children.empty?
memo << "</li>"
end.html_safe
end
end
It works fine. But I'm writing HTML inside a Ruby class and I don't like the idea, I'de like to keep it in the view. I tried to play with &block
to turn it like following
<ul>
<% Category.roots.each do |category| %>
<li class="col-md-2">
<a href="#"><%= category.name %></a>
<% if !category.children.empty? %>
<ul>
<% category.decorate.draw_tree do |child| %>
<li class="dir"><a href="#"><%= child.name %></a>
<% if child.children.any %>
<ul><%= child.decorate.draw_tree %></ul>"
<% end %>
</li>"
<% end %>
</ul>
<% end %>
</li>
<% end %>
</ul>
Sadly, I couldn't make it work so far. I think I lack methodology here. How can I rewrite this code ?