Class: Tabelr::TableFormator

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

Instance Method Summary collapse

Constructor Details

#initializeTableFormator

Returns a new instance of TableFormator.



4
5
6
7
# File 'lib/tabelr/table_formater.rb', line 4

def initialize
  @lines = []
  @line = []
end

Instance Method Details

#analyseObject



43
44
45
46
47
48
49
50
# File 'lib/tabelr/table_formater.rb', line 43

def analyse
  @max_len = []
  @lines.each do |line|
    line.each_with_index do |item, i|
      @max_len[i] = max @max_len[i], item.to_s.length
    end
  end
end

#bankObject



19
20
21
22
# File 'lib/tabelr/table_formater.rb', line 19

def bank
  @lines << @line.dup
  @line.clear
end

#convert(json) ⇒ Object



9
10
11
12
13
# File 'lib/tabelr/table_formater.rb', line 9

def convert json
  parse json
  analyse
  dump
end

#dividerObject



76
77
78
79
80
# File 'lib/tabelr/table_formater.rb', line 76

def divider
  s = "+"
  @max_len.each { |n| s += "-" * (n+2) + "+" }
  s += "\n"
end

#dumpObject



52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/tabelr/table_formater.rb', line 52

def dump
  output = ""
  output << divider
  @lines.each_with_index do |line, index|
    output << divider if index == 1
    line.each_with_index do |item, i|
      output << format(item.to_s, @max_len[i])
    end
    output << "|\n"
  end
  output << divider
end

#format(text, count) ⇒ Object



72
73
74
# File 'lib/tabelr/table_formater.rb', line 72

def format text, count
  "| #{text} " + " " * (count-text.length)
end

#max(a, b) ⇒ Object



65
66
67
68
69
70
# File 'lib/tabelr/table_formater.rb', line 65

def max a, b
  return a if b.nil?
  return b if a.nil?
  return a if a > b
  b
end

#parse(json) ⇒ Object



24
25
26
27
# File 'lib/tabelr/table_formater.rb', line 24

def parse json
  @header = true
  json.each_value { |h| parse_hash h }
end

#parse_hash(hash) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/tabelr/table_formater.rb', line 29

def parse_hash hash
  if @header
    hash.first.each_key { |key| stash key }
    bank
    @header = false
  end

  # content/row
  hash.each do |line|
    line.each_value { |value| stash value }
    bank
  end
end

#stash(data) ⇒ Object



15
16
17
# File 'lib/tabelr/table_formater.rb', line 15

def stash data
  @line << data
end