Class: AlignedTable

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

Constant Summary collapse

VERSION =
"0.1.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeAlignedTable

Returns a new instance of AlignedTable.



6
7
8
# File 'lib/aligned_table.rb', line 6

def initialize
  @separator = " "
end

Instance Attribute Details

#rowsObject

Returns the value of attribute rows.



4
5
6
# File 'lib/aligned_table.rb', line 4

def rows
  @rows
end

#separatorObject

Returns the value of attribute separator.



4
5
6
# File 'lib/aligned_table.rb', line 4

def separator
  @separator
end

#titleObject

Returns the value of attribute title.



4
5
6
# File 'lib/aligned_table.rb', line 4

def title
  @title
end

Instance Method Details

#column_lengthsObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/aligned_table.rb', line 25

def column_lengths
  columns = []

  @rows.each do |row|
    row.each_with_index do |col, index|
      columns[index] ||= []
      columns[index] << col
    end
  end

  columns.map! do |col|
    col.map { |x| x.to_s }.max_by(&:length).length
  end

  columns
end

#renderObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/aligned_table.rb', line 10

def render
  col_len = column_lengths
  rows = @rows.map do |row|
    render_row(row, col_len)
  end

  max_row_length = rows.max_by(&:length).length

  if @title
    rows.unshift(" #@title ".center(max_row_length, "="))
  end

  rows.join("\n")
end

#render_row(row, col_len) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/aligned_table.rb', line 42

def render_row(row, col_len)
  columns = row.each_with_index.map do |col, index|
    if col.is_a?(Symbol)
      col.to_s * col_len[index]
    else
      if index == 0
        col.to_s.rjust(col_len[index])
      else
        col.to_s.ljust(col_len[index])
      end
    end
  end
  columns.join(@separator)
end