Class: Strobe::CLI::Table

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

Defined Under Namespace

Classes: Index

Instance Method Summary collapse

Constructor Details

#initialize(collection, opts = {}) ⇒ Table

Returns a new instance of Table.


5
6
7
8
9
10
11
12
13
14
# File 'lib/strobe/cli/table.rb', line 5

def initialize(collection, opts = {})
  @collection = collection
  @columns    = []
  @computed   = []
  @opts       = opts

  if opts[:index]
    @columns.unshift({ :key => Index, :max => 0 })
  end
end

Instance Method Details

#column(key, opts = {}, &blk) ⇒ Object


16
17
18
# File 'lib/strobe/cli/table.rb', line 16

def column(key, opts = {}, &blk)
  @columns << { :key => key, :max => 0, :blk => blk }.merge(opts)
end

#to_sObject


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
55
# File 'lib/strobe/cli/table.rb', line 20

def to_s
  @collection.each do |obj|
    @computed << @columns.map do |col|
      if col[:blk]
        cell = col[:blk].call(obj)
      elsif col[:key] != Index
        cell = obj[ col[:key] ]
      end

      cell = cell.to_s
      col[:max] = [ cell.length, col[:max] ].max
      cell
    end
  end

  if @computed.empty?
    return @opts[:empty] || "Nothing to see here..."
  end

  str = ""

  @columns.each do |col|
    cell = (col[:header] || col[:key]).to_s.upcase unless col[:key] == Index
    str << cell_to_s(col, cell)
  end

  str << "\n"

  @computed.each_with_index do |cells, i|
    cells.each_with_index do |cell, j|
      str << cell_to_s(@columns[j], cell, i)
    end
    str << "\n"
  end
  str
end