I have a pattern in a couple of templates that's repeated. The code is for rendering a set of tabs and content for each tab.
Contents of /app/views/general/_product_groupings.html.erb
<table cellpadding="1" cellspacing="0" class="sub_container clear">
<tr>
<% first_visible_tab = true %>
<% @bundle.groupings.each do |group| %>
<td id="tab_heading_for_group_<%= group.id %>" class="tab_heading <%= 'selected' if first_visible_tab %>" onclick="show_tab('product_type_<%= group.id %>')"><%= one_liner(group.name) %></td>
<td></td>
<% first_visible_tab = false %>
<% end %>
<td class="last"></td>
</tr>
<tr>
<td colspan="99" class="tab_content">
<% first_visible_tab = true %>
<%# groupings is an array of products %>
<% @bundle.groupings.each do |group| %>
<div style="display: <%= (first_visible_tab) ? '' : 'none' %>" id="tab_body_for_group_<%= group.id %>" class="tab_body container_inner">
<% first_visible_tab = false %>
<% template = case group.grouping_type
when 'selection'
:product_selection_group
when 'group'
:product_optional_group
when 'product'
:product_optional_group
end %>
<%= render :partial => template.to_s, :locals => {:group => group} %>
</div>
<% end %>
</td>
<tr>
</table>
The code consists of some parts. There is the general parameter passed in, @bundle
. There is a header section (lines 1-10):
<table cellpadding="1" cellspacing="0" class="sub_container clear">
<tr>
<% first_visible_tab = true %>
<% @bundle.groupings.each do |group| %>
<td id="tab_heading_for_group_<%= group.id %>" class="tab_heading <%= 'selected' if first_visible_tab %>" onclick="show_tab('product_type_<%= group.id %>')"><%= one_liner(group.name) %></td>
<td></td>
<% first_visible_tab = false %>
<% end %>
<td class="last"></td>
</tr>
In the header section, there are parts that differ each place code like this is used: The collection iterated upon, @bundle.groupings
. The parameter for show_tab()
onclick. The id of the tab id="tab_heading_for_group_<%= group.id %>"
.
Below the header, there is an area that i reckon could be yielded as a block, the real content of each tab content area (lines 19-27):
<% template = case group.grouping_type
when 'selection'
:product_selection_group
when 'group'
:product_optional_group
when 'product'
:product_optional_group
end %>
<%= render :partial => template.to_s, :locals => {:group => group} %>
Just above the content is the same collection @bundle.groupings.each do ...
repeated from the head section.
I would really much like to DRY this up. By defining a block with the content that can be yielded inside a helper method.
I think this method should take the following params:
- id_template
- onclick_method #perhaps with a pattern for the parameter to the onclick method
- collection
- block to be yielded inside the content area of the tab
Question is, how do I make a helper method to take both block and params?