Created
April 12, 2015 18:04
-
-
Save amleaver/558b2c086eaa5e4725c5 to your computer and use it in GitHub Desktop.
Rails partial for an object as an HTML table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- | |
Renders an object as an HTML table (developed under Rails 4.0). | |
locals: | |
* object: The object to render | |
* 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 the 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: "object_as_table", | |
locals: { | |
object: @user, | |
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? | |
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 object.present? %> | |
<table id="<%= table_id %>" class="<%= table_class %>" style="<%= table_style %>"> | |
<thead/> | |
<tbody> | |
<% object.attributes.each do |key, value| %> | |
<% next if ignore.include?(key.to_sym) %> | |
<tr> | |
<td><%= key.humanize %></td> | |
<td><%= value %></td> | |
</tr> | |
<% end %> | |
<% calls.each do |call| %> | |
<tr> | |
<% if call.kind_of?(Array) %> | |
<td> | |
<%= call.last.humanize %> | |
</td> | |
<td> | |
<%= object.instance_eval(call.first) rescue nil %> | |
</td> | |
<% else %> | |
<td> | |
<%= call.humanize %> | |
</td> | |
<td> | |
<%= object.instance_eval(call) rescue nil %> | |
</td> | |
<% end %> | |
</tr> | |
<% end %> | |
</tbody> | |
</table> | |
<% end %> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment