Class: TableLayouts::Nice

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

Overview

Nice layout

Instance Method Summary collapse

Constructor Details

#initialize(headers, data) ⇒ Nice

Returns a new instance of Nice.



7
8
9
10
# File 'lib/table_layouts.rb', line 7

def initialize(headers, data)
  @headers = headers
  @data = data
end

Instance Method Details

#find_max_column_widthsObject



12
13
14
15
16
17
18
19
# File 'lib/table_layouts.rb', line 12

def find_max_column_widths
  all = [@headers] + @data
  longest_row = all.inject(0) { |max, row| [row.length, max].max }
  init = Array.new(longest_row, 0)
  all.inject(init) do |memo, row|
    memo.zip(row.map(&:to_s).map(&:length)).map { |pair| pair.compact.max }
  end
end

#generate_separators(widths) ⇒ Object



38
39
40
# File 'lib/table_layouts.rb', line 38

def generate_separators(widths)
  widths.map { |width| '-' * width }
end

#layoutObject



21
22
23
24
25
26
27
28
29
30
# File 'lib/table_layouts.rb', line 21

def layout
  max_column_widths = find_max_column_widths
  padded_column_widths = max_column_widths.map { |w| w + 2 }
  padded_headers = pad_row(padded_column_widths, @headers)
  separators = generate_separators(padded_column_widths)
  padded_data = @data.map do |row|
    pad_row(padded_column_widths, row)
  end
  [padded_headers, separators] + padded_data
end

#pad_row(padded_column_widths, row) ⇒ Object



32
33
34
35
36
# File 'lib/table_layouts.rb', line 32

def pad_row(padded_column_widths, row)
  padded_column_widths.zip(row).map do |width, col|
    " #{col}".ljust(width)
  end
end