Skip to content

Instantly share code, notes, and snippets.

@samwgoldman
Created September 7, 2011 05:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samwgoldman/1199827 to your computer and use it in GitHub Desktop.
Save samwgoldman/1199827 to your computer and use it in GitHub Desktop.
Create an html table with shorthand syntax
def html_table(tableish)
unless tableish.map(&:size).uniq.count == 1
raise 'Must be array of arrays of equal length'
end
table = Nokogiri::HTML::DocumentFragment.parse ''
Nokogiri::HTML::Builder.with(table) { |html|
html.table {
if tableish.first.size > 1
html.thead {
html.tr {
tableish.map(&:shift).each { |header| html.th header }
}
}
end
html.tbody {
tableish.first.size.times do
html.tr {
tableish.map(&:shift).each { |data| html.td { html << data } }
}
end
}
}
}
table.to_html.gsub(/\n\s*/, '')
end
# examples
html_table([['Name', 'Example Project']]) # => <table><thead><tr><th>Name</th></tr></thead><tbody><tr><td>Example Project</td></tr></tbody></table>
html_table([['Name', 'Example Project'],['Tasks', html_table([['Name', 'Example Task', 'Example Task']])]]) # => <table><thead><tr><th>Name</th><th>Tasks</th></tr></thead><tbody><tr><td>Example Project</td><td><table><thead><tr><th>Name</th></tr></thead><tbody><tr><td>Example Task</td></tr><tr><td>Example Task</td></tr></tbody></table></td></tr></tbody></table>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment