Module: Termline::Table

Defined in:
lib/termline/table.rb

Class Method Summary collapse

Class Method Details

.builder(data, header: true) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/termline/table.rb', line 36

def builder data, header:true

    return if Gem.win_platform?
    return unless data.size > 0

    table_from_array = true if data.first.class == Array
    header = false if table_from_array

    if data.class.name == "ActiveRecord::Relation"
        data = data.to_a.map(&:serializable_hash) 
    end

    # get the available characters in terminal width
    #terminal_width = `tput cols`.to_i
    terminal_width = Style::WIDTH

    # get the number of columns to print base on the data hash
    cols = data.first.length + 1

    # get the available space for every column
    col_width = (terminal_width / cols) - 1

    # validate that we have minimum space to render the table
    return if col_width <= 0

    # separator for every column and row
    separator = ('| ' << ('- ' * (col_width / 2)))

    # add extra blank spaces to adjust the col_width only if col_width not a even number
    separator += (' ') if (col_width - separator.size).odd?

    # only for table header
    if header

        # print table titles
        puts '| ' << data.first.keys.map { |key| key.to_s.upcase.ljust(col_width) }.join('| ')
    end 

    # print header separators, only for visible columns
    puts separator * (cols - 1)

    # print data as table :)
    data.each_with_index do |row, index|

        # join hash values as a line and justify every value to print value in its own column
        puts '| ' << row.values.map { |value| value.to_s.ljust(col_width) }.join('| ') unless table_from_array

        # print simple value from the array data
        puts '| ' << row.map { |value| value.to_s.ljust(col_width) }.join('| ') if table_from_array
    end

    puts separator * (cols - 1) unless header
end