Module: Frecli::Table

Defined in:
lib/frecli/table.rb

Class Method Summary collapse

Class Method Details

.horizontal(record, items) ⇒ Object

Table where heading is in the first column, and value in the second.

When records = [ { id: 1, name: ‘Hello’, body: ‘Hello, world!’ } ]

items   = [ { ID: :id, Name: :name, Body: :body } ]

---------------------- | ID | 1 | | Name | Hello | | Body | Hello, world! | ----------------------



36
37
38
39
40
41
42
# File 'lib/frecli/table.rb', line 36

def self.horizontal(record, items)
  Terminal::Table.new do |table|
    table.rows = items.map do |name, value|
      [name, table_item(record, value)]
    end
  end
end

.table_item(record, value) ⇒ Object

When record = { id: 1, name: ‘Hello’, body: ‘Hello, world!’ }

value  = :id
      => 1

value  = -> (record) { record.name.upcase }
      => 'HELLO'

value  = 'foo'
      => 'foo'


54
55
56
57
58
59
# File 'lib/frecli/table.rb', line 54

def self.table_item(record, value)
  return record[value] if value.is_a? Symbol
  return value[record] if value.respond_to? :call

  value
end

.vertical(records, headings, values) ⇒ Object

Table where heading is in the first row, and values are in the columns

When records = [ { id: 1, name: ‘Hello’, body: ‘Hello, world!’ } ]

headings =  'ID', 'Name', 'Body']
values   =  [ :id, :name, :body]

---------------------------- | ID | Name | Body | ---------------------------- | 1 | Hello | Hello, world! | ----------------------------



16
17
18
19
20
21
22
23
24
# File 'lib/frecli/table.rb', line 16

def self.vertical(records, headings, values)
  Terminal::Table.new do |table|

    table.headings = headings
    table.rows = records.map do |record|
      values.map { |value| table_item(record, value)}
    end
  end
end