Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.