Class: TheFox::Timr::Table

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = Hash.new) ⇒ Table

Returns a new instance of Table.



10
11
12
13
14
# File 'lib/timr/table.rb', line 10

def initialize(options = Hash.new)
	@headings = options.fetch(:headings, Array.new)
	
	@rows = Array.new
end

Instance Attribute Details

#rowsObject (readonly)

Holds all rows.



8
9
10
# File 'lib/timr/table.rb', line 8

def rows
  @rows
end

Instance Method Details

#<<(row) ⇒ Object

Append a row.



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/timr/table.rb', line 17

def <<(row)
	col_n = 0
	row.each do |col|
		header = @headings[col_n]
		if header
			header[:format] ||= '%s'
			header[:label] ||= ''
			unless header.has_key?(:empty)
				header[:empty] = true
			end
			header[:max_length] ||= 0
			header[:padding_left] ||= ''
			header[:padding_right] ||= ''
		else
			header = {
				:format => '%s',
				:label => '',
				:empty => true,
				:max_length => 0,
				:padding_left => '',
				:padding_right => '',
			}
		end
		
		unless col.nil?
			if header[:empty]
				header[:empty] = false
			end
			col_s = col.to_s
			if col_s.length > header[:max_length]
				header[:max_length] = (header[:format] % [col_s]).length + header[:padding_left].length + header[:padding_right].length
			end
		end
		
		col_n += 1
	end
	@rows << row
end

#to_sObject

Render Table to String.



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
# File 'lib/timr/table.rb', line 57

def to_s
	s = ''
	
	s << @headings.map{ |header|
		unless header[:empty]
			"%s#{header[:format]}%s" % [header[:padding_left], header[:label], header[:padding_right]]
		end
	}.select{ |ts| !ts.nil? }.join(' ')
	s << "\n"
	
	@rows.each do |row|
		col_n = 0
		columns = []
		row.each do |col|
			header = @headings[col_n]
			unless header[:empty]
				col_s = "%s#{header[:format]}%s" % [header[:padding_left], col, header[:padding_right]]
				
				columns << col_s
			end
			col_n += 1
		end
		s << columns.join(' ') << "\n"
	end
	
	s
end