Class: Daemonizer::Stats::Table

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

Overview

Container for tabular data.

Instance Method Summary collapse

Constructor Details

#initialize(column_names) ⇒ Table

Returns a new instance of Table.



40
41
42
43
# File 'lib/daemonizer/stats.rb', line 40

def initialize(column_names)
	@column_names = column_names
	@rows = []
end

Instance Method Details

#add_row(values) ⇒ Object



45
46
47
# File 'lib/daemonizer/stats.rb', line 45

def add_row(values)
	@rows << values.to_a
end

#add_rows(list_of_rows) ⇒ Object



49
50
51
52
53
# File 'lib/daemonizer/stats.rb', line 49

def add_rows(list_of_rows)
	list_of_rows.each do |row|
		add_row(row)
	end
end

#remove_column(name) ⇒ Object



55
56
57
58
59
60
61
# File 'lib/daemonizer/stats.rb', line 55

def remove_column(name)
	i = @column_names.index(name)
	@column_names.delete_at(i)
	@rows.each do |row|
		row.delete_at(i)
	end
end

#to_s(title = nil) ⇒ Object



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
# File 'lib/daemonizer/stats.rb', line 63

def to_s(title = nil)
	max_column_widths = [1] * @column_names.size
	(@rows + [@column_names]).each do |row|
		row.each_with_index do |value, i|
			max_column_widths[i] = [value.to_s.size, max_column_widths[i]].max
		end
	end

	format_string = max_column_widths.map{ |i| "%#{-i}s" }.join("  ")
	header = sprintf(format_string, *@column_names).rstrip << "\n"
	if title
		free_space = header.size - title.size - 2
		if free_space <= 0
			left_bar_size = 3
			right_bar_size = 3
		else
			left_bar_size = free_space / 2
			right_bar_size = free_space - left_bar_size
		end
		result = "#{BLUE_BG}#{BOLD}#{YELLOW}\n"
		result << "#{"-" * left_bar_size} #{title} #{"-" * right_bar_size}\n"
		if !@rows.empty?
			result << WHITE
			result << header
		end
	else
		result = header.dup
	end
	if @rows.empty?
		result << RESET
	else
		result << ("-" * header.size) << "#{RESET}\n"
		@rows.each do |row|
			result << sprintf(format_string, *row).rstrip << "\n"
		end
	end
	result
end