-
-
Save vrinek/0379b07f516f4f322204 to your computer and use it in GitHub Desktop.
A little DSL (almost) to create HTML tables
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
class Deepthought::DSL::Table | |
def initialize(array, &block) | |
return self if array.empty? | |
@field_names = [] | |
@array = array | |
@block = block | |
return table | |
end | |
def table | |
tbody # needs to be called to realize the headers for thead | |
"<table class=\"genTable\">\n" + thead + tbody + "</table>\n" | |
end | |
def field(name, inside = nil) | |
@field_names << name unless @field_names.include?(name) | |
@tr << "\t\t\t<td>#{inside or @record[name.to_sym]}</td>\n" | |
end | |
def to_s | |
table.to_s | |
end | |
def tbody | |
return @tbody if @tbody | |
@tbody = "\t<tbody>\n" + | |
@array.map do |record| | |
class_name = record.class.to_s.underscore | |
@tr = "\t\t<tr id=\"#{class_name}-#{record.id}\" class=\"#{class_name}\">\n" | |
@record = record | |
@block.call(self, record) | |
@tr + "\t\t</tr>\n" | |
end.join | |
end | |
def thead | |
"\t<thead>\n"+ | |
"\t\t<tr>\n" + | |
@field_names.map do |attr| | |
"\t\t\t<th>#{attr.to_s.titleize}</th>\n" | |
end.join + | |
"\t\t</tr>\n\t</thead>\n" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment