Class: PryParsecom::Table

Inherits:
Object
  • Object
show all
Defined in:
lib/pry-parsecom/table.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(heads, indent = ' ', rows = []) ⇒ Table

Returns a new instance of Table.



5
6
7
8
9
10
11
12
13
# File 'lib/pry-parsecom/table.rb', line 5

def initialize heads, indent='  ', rows=[]
  @heads = heads
  @indent = indent
  @col_widths = Hash.new 0
  @heads.each do |head|
    @col_widths[head] = head.size
  end
  self.rows = rows
end

Instance Attribute Details

#indentObject

Returns the value of attribute indent.



3
4
5
# File 'lib/pry-parsecom/table.rb', line 3

def indent
  @indent
end

Instance Method Details

#add_row(row) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/pry-parsecom/table.rb', line 22

def add_row row
  cols = []
  case row
  when Hash
    @heads.each do |head|
      cols << row[head]
    end
  when Array
    cols = row
  else
    cols = [row]
  end

  cols.each.with_index do |col, i|
    if @col_widths[i] < col.size
      @col_widths[i] = col.size
    end
  end
  @rows << cols
end

#rows=(rows) ⇒ Object



15
16
17
18
19
20
# File 'lib/pry-parsecom/table.rb', line 15

def rows= rows
  @rows = []
  rows.each do |row|
    add_row row
  end
end

#to_sObject



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/pry-parsecom/table.rb', line 43

def to_s
  heads = @heads.map.with_index do |head, i|
    head.center @col_widths[i]
  end.join " | "
  ret = heads
  ret += "\n"
  ret += '=' * heads.size
  ret += "\n"
  @rows.each do |row|
    ret += row.map.with_index { |col, i|
      col.ljust @col_widths[i]
    }.join " | "
    ret += "\n"
  end
  ret.gsub /^/, @indent
end