Class: MDTable

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

Constant Summary collapse

VERSION =
'0.0.2'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(rows) ⇒ MDTable

Returns a new instance of MDTable.



22
23
24
# File 'lib/mdtable.rb', line 22

def initialize rows
  @rows = rows
end

Class Method Details

.convert(rows) ⇒ Object

convert 2D array to md table array

rows - array of array

Examples:

MDTable.convert [[1,2,3], ['x', 'x', 'x']]
# => ['1 | 2 | 3',
      '- | - | -',
      'x | x | x']

Returns an array of string as a markdown table



17
18
19
20
# File 'lib/mdtable.rb', line 17

def self.convert(rows)
  rows = rows.map {|row| row.map(&:to_s) }
  new(rows).to_md
end

Instance Method Details

#col_lengthsObject



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

def col_lengths
  @col_lengths ||= 0.upto(@rows.first.size - 1).map {|i|
    @rows.map {|r| r[i].length }.max
  }
end

#tableObject



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

def table
  @table ||= @rows.dup.insert(1, col_lengths.map {|l| '-' * l })
end

#to_mdObject



26
27
28
29
30
# File 'lib/mdtable.rb', line 26

def to_md
  table.map {|row|
    row.each_with_index.map {|item, i| item.ljust(col_lengths[i])}.join ' | '
  }
end