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.



44
45
46
47
# File 'lib/thamble.rb', line 44

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

Instance Method Details

#<<(row) ⇒ Object

Add a row to the table.



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

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

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

Create an a tag with the given text and href.



114
115
116
# File 'lib/thamble.rb', line 114

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.



119
120
121
# File 'lib/thamble.rb', line 119

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

#tag(*a) ⇒ Object

Create a Tag object from the arguments.



109
110
111
# File 'lib/thamble.rb', line 109

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

#to_sObject

Return a string containing the HTML table.



55
56
57
58
59
60
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
# File 'lib/thamble.rb', line 55

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]

  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(td, col, handle_proc(td_attr, col, i, row)).to_s
    end
    s << trh.close
  end
  s << "</tbody>\n"
  s << t.close
end