Class: Thamble::Table

Inherits:
Object
  • Object
show all
Defined in:
lib/thamble.rb

Overview

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

Instance Method Summary collapse

Constructor Details

#initialize(opts = OPTS) ⇒ Table

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



50
51
52
53
# File 'lib/thamble.rb', line 50

def initialize(opts=OPTS)
  @opts = opts
  @rows = []
end

Instance Method Details

#<<(row) ⇒ Object

Add a row to the table.



56
57
58
# File 'lib/thamble.rb', line 56

def <<(row)
  @rows << row
end

#a(text, href, opts = OPTS) ⇒ Object

Create an a tag with the given text and href.



121
122
123
# File 'lib/thamble.rb', line 121

def a(text, href, opts=OPTS)
  tag('a', text, opts.merge(:href=>href))
end

#raw(s) ⇒ Object

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



126
127
128
# File 'lib/thamble.rb', line 126

def raw(s)
  RawString.new(s)
end

#tag(*a) ⇒ Object

Create a Tag object from the arguments.



116
117
118
# File 'lib/thamble.rb', line 116

def tag(*a)
  Tag.tag(*a)
end

#to_sObject

Return a string containing the HTML table.



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/thamble.rb', line 61

def to_s
  empty = ''.freeze
  tr = 'tr'.freeze
  th = 'th'.freeze
  td = 'td'.freeze
  nl = "\n".freeze
  tr_attr = @opts[:tr]
  th_attr = @opts[:th]
  td_attr = @opts[:td]
  col_th = @opts[:column_th]

  t = tag('table', empty, @opts[:table])
  s = t.open.dup
  s << nl

  if caption = @opts[:caption]
    s << tag(:caption, caption).to_s
  end

  if widths = @opts[:widths]
    s << "<colgroup>\n"
    widths.each do |w|
      s << "<col width=\"#{w.to_i}\" />\n"
    end
    s << "</colgroup>\n"
  end

  if headers = @opts[:headers]
    s << "<thead>\n"
    headers = headers.split(',') if headers.is_a?(String)
    trh = tag(tr, empty, handle_proc(tr_attr, headers))
    s << trh.open
    s << nl
    headers.each_with_index do |header, i|
      s << tag(th, header, handle_proc(th_attr, header)).to_s
    end
    s << trh.close
    s << "</thead>\n"
  end

  s << "<tbody>\n"
  @rows.each do |row|
    trh = tag(tr, empty, handle_proc(tr_attr, row))
    s << trh.open
    s << nl
    row.each_with_index do |col, i|
      s << tag((col_th && i == 0 ? th : td), col, handle_proc(td_attr, col, i, row)).to_s
    end
    s << trh.close
  end
  s << "</tbody>\n"
  s << t.close
end