Skip to content

Instantly share code, notes, and snippets.

@vrinek
Created July 25, 2011 07:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrinek/0379b07f516f4f322204 to your computer and use it in GitHub Desktop.
Save vrinek/0379b07f516f4f322204 to your computer and use it in GitHub Desktop.
A little DSL (almost) to create HTML tables
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