Skip to content

Instantly share code, notes, and snippets.

@amleaver
Last active August 29, 2015 14:19
Show Gist options
  • Save amleaver/37711ab9a7c8e30d0754 to your computer and use it in GitHub Desktop.
Save amleaver/37711ab9a7c8e30d0754 to your computer and use it in GitHub Desktop.
Rails partial for rendering collections as an HTML table
<!--
Renders a collection of objects in an HTML table (developed under Rails 4.0).
locals:
* size: The size of the collection (required to determine when to close the table)
* ignore (optional): array of symbols which map to object attributes which won't be rendered in the table
* calls (optional): array of strings which map to methods to call against each object
* table_class (optional): class value to use for the table
* table_id (optional): id to use for the table
* style (optional): style value to use for the table
Example usage:
render partial: "collection_as_table", collection: @users, as: :item,
locals: {
size: @users.count,
ignore: [:updated_at, :created at],
calls: [['fullname'], ['is_admin.humanize', 'Is Admin?']],
table_class: 'tablesorter',
table_id: 'user',
style: 'background-color: white'
}
-->
<%
calls = [] if local_assigns[:calls].nil?
ignore = [] if local_assigns[:ignore].nil?
column_headers = item.attributes.keys
table_class = '' if local_assigns[:table_class].nil?
table_style = '' if local_assigns[:table_style].nil?
table_id = '' if local_assigns[:table_id].nil?
%>
<% if item_counter == 0 %>
<table id="<%= table_id %>" class="<%= table_class %>" style="<%= table_style %>">
<thead>
<tr>
<% column_headers.each do |header| %>
<% next if ignore.include?(header.to_sym) %>
<th><%= header.titleize %></th>
<% end %>
<% calls.each do |call| %>
<th>
<% if call.kind_of?(Array) %>
<%= call.last %>
<% else %>
<%= call.split('.').last.titleize %>
<% end %>
</th>
<% end %>
</tr>
</thead>
<tbody>
<% end %>
<tr>
<% item.attributes.each do |key, value| %>
<% next if ignore.include?(key.to_sym) %>
<td><%= value %></td>
<% end %>
<% calls.each do |call| %>
<td>
<% if call.kind_of?(Array) %>
<%= item.instance_eval(call.first) rescue nil %>
<% else %>
<%= item.instance_eval(call) rescue nil %>
<% end %>
</td>
<% end %>
</tr>
<% if item_counter == size - 1 %>
</tbody>
<tfoot>
</tfoot>
</table>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment