Class: TableFormatter

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

Overview

file: table-formatter.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source: nil, labels: nil, border: true, wrap: true, divider: nil, markdown: false) ⇒ TableFormatter

Returns a new instance of TableFormatter.



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/table-formatter.rb', line 9

def initialize(source: nil, labels: nil, border: true, wrap: true, 
               divider: nil, markdown: false)    

  super()
  @source = source
  @labels = labels
  @border = border
  @wrap = wrap
  @divider = divider
  @maxwidth = 60
  @markdown = markdown
  
end

Instance Attribute Details

#borderObject

Returns the value of attribute border.



7
8
9
# File 'lib/table-formatter.rb', line 7

def border
  @border
end

#dividerObject

Returns the value of attribute divider.



7
8
9
# File 'lib/table-formatter.rb', line 7

def divider
  @divider
end

#labelsObject

Returns the value of attribute labels.



7
8
9
# File 'lib/table-formatter.rb', line 7

def labels
  @labels
end

#markdownObject

Returns the value of attribute markdown.



7
8
9
# File 'lib/table-formatter.rb', line 7

def markdown
  @markdown
end

#sourceObject

Returns the value of attribute source.



7
8
9
# File 'lib/table-formatter.rb', line 7

def source
  @source
end

Instance Method Details

#display(width = nil, widths: nil, markdown: @markdown) ⇒ Object Also known as: to_s



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
56
57
58
# File 'lib/table-formatter.rb', line 23

def display(width=nil, widths: nil, markdown: @markdown)
  
  return display_markdown(@source, @labels) if markdown

  if @labels then

    @align_cols, labels = [], []

    @labels.each do |raw_label|

      col_just, label = just(raw_label)
      @align_cols << col_just
      labels << label
    end

  end

  #width ||= @maxwidth
  @width = width
  @maxwidth = width if width
  a = @source.map {|x| x.map{|y| y.length > 0 ? y : ' ' }}.to_a

  column_widths = widths ? widths : fetch_column_widths(a)

  column_widths[-1] -= column_widths.inject(&:+) - width if width

  records = format_rows(a, column_widths)

  div =  (border == true ? '-' : '') * records[0].length + "\n"
  label_buffer = ''
  
  label_buffer = format_cols(labels, column_widths) + "\n" + div if labels

  div + label_buffer + records.join("\n") + "\n" + div

end