Created
September 7, 2011 05:23
-
-
Save samwgoldman/1199827 to your computer and use it in GitHub Desktop.
Create an html table with shorthand syntax
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
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