Class: Simple::Printer

Inherits:
Object
  • Object
show all
Defined in:
lib/simple-printer.rb

Defined Under Namespace

Modules: Printable Classes: Field

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fields) ⇒ Printer

Returns a new instance of Printer.



11
12
13
# File 'lib/simple-printer.rb', line 11

def initialize(fields)
  @fields = fields.map { |s| Field.make(spec: s) }
end

Class Method Details



7
8
9
# File 'lib/simple-printer.rb', line 7

def self.print(*fields, **params)
  new(fields).print(**params)
end

Instance Method Details



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/simple-printer.rb', line 15

def print(output: STDOUT, indent: 0)
  output ||= StringIO.new
  max_label_width = @fields.map { |f| f.label.length }.max
  @fields.each do |field|
    output.puts '%s%*s:%s' % [
      ' ' * indent,
      max_label_width,
      field.label,
      field.value.nil? ? '' : " #{field.value}",
    ]
    if field.children
      field.children.each_with_index do |o, i|
        output.puts if i > 0
        o.print(output: output, indent: indent + 2 + max_label_width)
      end
    end
  end
  if output.kind_of?(StringIO)
    output.rewind
    output.read
  else
    nil
  end
end