Class: Hotdog::Formatters::Plain

Inherits:
BaseFormatter show all
Defined in:
lib/hotdog/formatters/plain.rb

Instance Method Summary collapse

Instance Method Details

#_format(result, sep, options = {}) ⇒ Object



42
43
44
45
46
# File 'lib/hotdog/formatters/plain.rb', line 42

def _format(result, sep, options={})
  result.map { |row|
    row.join(" ")
  }.join(sep)
end

#format(result, options = {}) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/hotdog/formatters/plain.rb', line 6

def format(result, options={})
  if options[:print0]
    sep = "\0"
  elsif options[:print1]
    sep = "\n"
  else
    sep = " "
  end
  if options[:print1] and options[:headers] and options[:fields]
    field_length = (0...result.last.length).map { |field_index|
      result.reduce(0) { |length, row|
        [length, row[field_index].to_s.length, options[:fields][field_index].to_s.length].max
      }
    }
    header_fields = options[:fields].zip(field_length).map { |field, length|
      field.to_s + (" " * (length - field.length))
    }
    result = [
      header_fields,
      header_fields.map { |field|
        "-" * field.length
      },
    ] + result.map { |row|
      row.zip(field_length).map { |field, length|
        field.to_s + (" " * (length - field.length))
      }
    }
  end
  s = _format(result, sep, options)
  if s.empty? or options[:print0]
    s
  else
    s + "\n"
  end
end