Class: PT::DataTable

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dataset, title = nil) ⇒ DataTable

Returns a new instance of DataTable.



10
11
12
13
# File 'lib/pt/data_table.rb', line 10

def initialize(dataset, title=nil)
  @title = title
  @rows = dataset.map{ |row| DataRow.new(row, dataset) }
end

Class Method Details

.fieldsObject



44
45
46
# File 'lib/pt/data_table.rb', line 44

def self.fields
  []
end

.headersObject



48
49
50
# File 'lib/pt/data_table.rb', line 48

def self.headers
  []
end

Instance Method Details

#[](pos) ⇒ Object



35
36
37
38
# File 'lib/pt/data_table.rb', line 35

def [](pos)
  pos = pos.to_i
  (pos < 1 || pos > @rows.length) ? nil : @rows[pos-1].record
end

#lengthObject



40
41
42
# File 'lib/pt/data_table.rb', line 40

def length
  @rows.length
end


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/pt/data_table.rb', line 15

def print(config={})
  if @rows.empty?
    puts "\n#{'-- empty list --'.center(36)}\n"
  else

    headers = [:num]
    headers += self.class.headers.present? ? self.class.headers : self.class.fields

    fields = [:num] + self.class.fields
    rows = []
    @rows.each_with_index do |row, index|
      _row = fields.map { |f| row.send(f) }
      rows << _row
    end
    table = Terminal::Table.new(title: @title, headings: headers,
                               rows: rows, style: { all_separators: true })
    puts table
  end
end