Class: Csv2md

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

Defined Under Namespace

Classes: UnableToParseCsv

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input) ⇒ Csv2md

Returns a new instance of Csv2md.



6
7
8
# File 'lib/csv2md.rb', line 6

def initialize(input)
  @input = input
end

Instance Attribute Details

#inputObject (readonly)

Returns the value of attribute input.



10
11
12
# File 'lib/csv2md.rb', line 10

def input
  @input
end

Instance Method Details

#csvObject



50
51
52
53
54
55
56
57
# File 'lib/csv2md.rb', line 50

def csv
  result = input.split("\n").map do |line|
    row = line.scan(/\|([^\|]*)\s/).flatten.map(&:strip).join(",")
    row unless row.strip == ""
  end.compact.join("\n")
  result += "\n"
  result
end

#find_column_widthsObject



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/csv2md.rb', line 12

def find_column_widths
  parsed_csv.inject(Array.new(parsed_csv[0].length, 0)) do |result, line|
    line.each_with_index do |column, i|
      if column.to_s.length > result[i]
        result[i] = column.length
      end
    end

    result
  end
rescue
  raise UnableToParseCsv
end

#gfmObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/csv2md.rb', line 26

def gfm
  result = ""
  widths = find_column_widths
  number_of_columns = widths.length

  parsed_csv.each_with_index do |line, row_index|
    line.each_with_index do |column, column_index|
      result += "| "
      result += column.to_s.ljust(widths[column_index] + 1, " ")
      if column_index == number_of_columns - 1
        result += "|\n"
      end
    end
    if row_index == 0
      widths.each do |width|
        result += "|".ljust(width + 3, "-")
      end
      result += "|\n"
    end
  end

  result
end