DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Ruby HTML Table Helper

09.28.2009
| 5179 views |
  • submit to reddit
         Ruby HTML table helper (generates TD's and TR's) 
 (note, the non-breaking space character in the table function has a typo you must fix, as I couldn't figure out how to escape it)

  <%=table(
    ['first','Norm'],
    ['middle','foo'],
    ['last','DePloom'],
    :th=>false, :table=>"class='datagrid'")%>
 
  <%=table(
    ['first','last'],
    ['johan','smith'],
    ['jim','jorgenson'])%>

  <%=table(
    ['first','last'],
    ['johan','smith'],
    ['jim','jorgenson'], {:th=>false, :tr=>"border='10'"})%>
  # creates an html table with tr and td tags by passing in args. 
  # Each row is an array.
  # The first gets th tags unless :th=>false is specified
  # options: The last item may be an options hash.  The options 
  # :tr, :td, and :table allow insertion of arbitrary attributes 
  # into the html of their respective tags.
  # If there are rows with too few items the columns are printed as  

 def table(*args)
   opts=args.last.is_a?(Hash) ? args.delete_at(args.length - 1) : {}
   rows=args
   [:table,:tr,:td].each {|sym| opts[sym]= " #{opts[sym]} " if opts[sym]}
   maxcols = rows.inject(0) {|memo,row| row.length > memo ? row.length : memo  }
   rows.map {|row|(maxcols-row.length).times{ row << "& nbsp;"};row }
   rows=rows.map{|row| row.sandwich("\t\t<td#{opts[:td]}>","</td>\n") }
   rows[0].gsub!('td','th') unless opts[:th] == false
   return ("<table#{opts[:table]}>\n" + rows.sandwich("\t<tr#{opts[:tr]}>\n","\t</tr>\n") + "</table>\n")
 end

# Needs:

class Array 
	# wraps the items in the array in a 
	# pre and post string, like ['foo','bar','baz'].sandwich('<td>','</td>')
	# => "<td>foo</td><td>bar</td><td>baz</td>"
	def sandwich(str1, str2)
		map{|item| "#{str1}#{item}#{str2}"}.join("")
	end
end