Class: GitGo::Formatter

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

Class Method Summary collapse

Class Method Details

.columns(array, options = {}) ⇒ String

Creates a nice column format to output an Array to the console.

Parameters:

  • array (Array)

    the Array to output in a column format.

  • options (Hash) (defaults to: {})

    the options to create the column format with.

Options Hash (options):

  • :spacing (Integer) — default: 4

    the amount of spaces between the columns.

  • :header (true, false) — default: false

    whether there is a header present or not.

Returns:

  • (String)

    the formatted Array.



13
14
15
16
17
18
19
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
# File 'lib/git_go/formatter.rb', line 13

def self.columns(array, options = {})
  options[:spacing] ||= 4
  options[:header]  ||= false

  columns        = 1
  column_lengths = []
  out            = ""

  array.each { |row| columns = row.length if row.length > columns }

  columns.times do |i|
    array.each do |row|
      column_lengths[i] ||= 0
      column_lengths[i] = row[i].length if row[i].length > column_lengths[i]
    end
  end

  array.each_with_index do |row, row_index|
    row.each_with_index do |column, index|
      column_spacing = index + 1 == columns ? 0 : options[:spacing]
      fill           = column_lengths[index] - column.length

      out << column + " " * (fill + column_spacing)
      out << "\n" if index + 1 == columns
    end

    if options[:header]
      row.each_with_index do |column, index|
        if row_index == 0
          column_spacing = index + 1 == columns ? 0 : options[:spacing]
          out << "-" * column_lengths[index] + " " * column_spacing
        end

        out << "\n" if index + 1 == columns && row_index == 0
      end
    end
  end

  out
end