Class: RTUI::Table

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

Instance Method Summary collapse

Constructor Details

#initialize(title, items, *fields) ⇒ Table

Returns a new instance of Table.



3
4
5
6
7
# File 'lib/rtui/table.rb', line 3

def initialize(title, items, *fields)
  @title = title
  @items = items
  @fields = fields
end

Instance Method Details



10
11
12
13
14
15
16
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
# File 'lib/rtui/table.rb', line 10

def print
  return if @items.empty?
  puts @title
  #find max length for each field; start with the field names themselves
  @fields = @items.first.class.column_names unless @fields.any?
  max_len = Hash[*@fields.map {|f| [f, f.to_s.length]}.flatten]
  @items.each do |item|
    @fields.each do |field|
      len = item.send(field).to_s.length
      max_len[field] = len if len > max_len[field]
    end
  end

  border = '+-' + @fields.map {|f| '-' * max_len[f] }.join('-+-') + '-+'
  title_row = '| ' + @fields.map do |f|
    sprintf("%-#{max_len[f]}s", f.to_s.split("_")[0].capitalize)
  end.join(' | ') + ' |'

  puts border
  puts title_row
  puts border

  @items.each do |item|
    row = '| ' + @fields.map do |f|
      sprintf("%-#{max_len[f]}s", item.send(f))
    end.join(' | ') + ' |'
    puts row
  end

  puts border
  puts "#{@items.length} items\n"
end