Over a million developers have joined DZone.

Helper For Quicly Creating Standard Tables

I often want to display an array of objects as a table on a page, and I end up doing the the same things over and over again. I wrote this helper method to speed things up:

def table(collection, headers, options = {}, &proc)
    :placeholder  => 'Nothing to display',
    :caption      => nil,
    :summary      => nil,
    :footer       => ''
  placeholder_unless collection.any?, options[:placeholder] do
    summary = options[:summary] || "A list of #{collection.first.class.to_s.pluralize}"
    output = "\n"
    output << content_tag('caption', options[:caption]) if options[:caption]
    output << "\t\n" if options[:caption]
    output << content_tag('thead', content_tag('tr', headers.collect { |h| "\n\t" + content_tag('th', h) }))
    output << "" + content_tag('th', options[:footer], :colspan => headers.size) + "\n" if options[:footer]
    output << "\n"
    concat(output, proc.binding)
    collection.each do |row|
      proc.call(row, cycle('odd', 'even'))
\n", proc.binding) end end
Writing... <% table(@posts, %w{ID title}) do |post, klass| -%> <%= post.id <%= post.title <% end -%> results in...
ID Title
1 My first post
Or, when the collection is an empty array (collection.any? returns false), a placeholder message is displayed:

Nothing to display

So you pass in your collection and an array of strings as your table headers as the first two arguments, and the third is a hash of options you can use to set the contents of the table's summary-attribute, the caption and footer-elements and the placeholder. The summary attribute defaults to "A list of [objects]", where 'objects' is derived from the class name of the collection. The function finally takes a block for every element in the collection, yeilding it the element and either 'odd' or 'even' so you can use CSS-classes to apply a zebra stripes effect.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}