Module: ToMd::TableBuilder

Defined in:
lib/to_md.rb

Class Method Summary collapse

Class Method Details

.build(header, items) ⇒ Object



27
28
29
30
31
32
33
# File 'lib/to_md.rb', line 27

def build header, items
  [
    row(header),
    row(header.map{'---'}),
    *items.map{|item|row item_to_array(header, item)}
  ].join($/)+$/
end

.build_with_hash(items) ⇒ Object



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

def build_with_hash items
  keys = items.map(&:keys).inject(:|)
  build keys, items
end

.escape_cell(text) ⇒ Object



48
49
50
# File 'lib/to_md.rb', line 48

def escape_cell text
  text.to_s.gsub('|', '|').gsub($/, '
')
end

.item_to_array(header, item) ⇒ Object



35
36
37
38
39
40
41
42
# File 'lib/to_md.rb', line 35

def item_to_array header, item
  if Hash === item
    header.map{|key|item[key]}
  else
    item = [*item] unless Array === item
    header.zip(item).map(&:last)
  end
end

.row(array) ⇒ Object



44
45
46
# File 'lib/to_md.rb', line 44

def row array
  '| '+array.map{|c|escape_cell c}.join(' | ')+' |'
end