class Thamble::Table

The Table class stores the rows and attributes to use for the HTML tags, and contains helper methods for common formatting.

Public Class Methods

new(opts=OPTS) click to toggle source

Create a new Table instance. Usually not called directly, but through Thamble.table.

   # File lib/thamble.rb
44 def initialize(opts=OPTS)
45   @opts = opts
46   @rows = []
47 end

Public Instance Methods

<<(row) click to toggle source

Add a row to the table.

   # File lib/thamble.rb
50 def <<(row)
51   @rows << row
52 end
a(text, href, opts=OPTS) click to toggle source

Create an a tag with the given text and href.

    # File lib/thamble.rb
115 def a(text, href, opts=OPTS)
116   tag('a', text, opts.merge(:href=>href))
117 end
raw(s) click to toggle source

Return a Raw string, which won't be HTML escaped.

    # File lib/thamble.rb
120 def raw(s)
121   RawString.new(s)
122 end
tag(*a) click to toggle source

Create a Tag object from the arguments.

    # File lib/thamble.rb
110 def tag(*a)
111   Tag.tag(*a)
112 end
to_s() click to toggle source

Return a string containing the HTML table.

    # File lib/thamble.rb
 55 def to_s
 56   empty = ''.freeze
 57   tr = 'tr'.freeze
 58   th = 'th'.freeze
 59   td = 'td'.freeze
 60   nl = "\n".freeze
 61   tr_attr = @opts[:tr]
 62   th_attr = @opts[:th]
 63   td_attr = @opts[:td]
 64   col_th = @opts[:column_th]
 65 
 66   t = tag('table', empty, @opts[:table])
 67   s = t.open.dup
 68   s << nl
 69 
 70   if caption = @opts[:caption]
 71     s << tag(:caption, caption).to_s
 72   end
 73 
 74   if widths = @opts[:widths]
 75     s << "<colgroup>\n"
 76     widths.each do |w|
 77       s << "<col width=\"#{w.to_i}\" />\n"
 78     end
 79     s << "</colgroup>\n"
 80   end
 81 
 82   if headers = @opts[:headers]
 83     s << "<thead>\n"
 84     headers = headers.split(',') if headers.is_a?(String)
 85     trh = tag(tr, empty, handle_proc(tr_attr, headers))
 86     s << trh.open
 87     s << nl
 88     headers.each_with_index do |header, i|
 89       s << tag(th, header, handle_proc(th_attr, header)).to_s
 90     end
 91     s << trh.close
 92     s << "</thead>\n"
 93   end
 94 
 95   s << "<tbody>\n"
 96   @rows.each do |row|
 97     trh = tag(tr, empty, handle_proc(tr_attr, row))
 98     s << trh.open
 99     s << nl
100     row.each_with_index do |col, i|
101       s << tag((col_th && i == 0 ? th : td), col, handle_proc(td_attr, col, i, row)).to_s
102     end
103     s << trh.close
104   end
105   s << "</tbody>\n"
106   s << t.close
107 end

Private Instance Methods

handle_proc(pr, *a) click to toggle source

If pr is a Proc or Method, call it with the given arguments, otherwise return it directly.

    # File lib/thamble.rb
128 def handle_proc(pr, *a)
129   case pr
130   when Proc, Method
131     pr.call(*a)
132   else
133     pr
134   end
135 end