Module: CommandKit::Printing::Fields

Includes:
Indent
Defined in:
lib/command_kit/printing/fields.rb

Overview

Supports printing aligned key/value fields.

Since:

  • 0.4.0

Instance Method Summary collapse

Methods included from Indent

#indent, #initialize, #puts

Instance Method Details

Prints a Hash as left-justified : separated fields.

Examples:

print_fields('Name' => 'foo', 'Version' => '0.1.0')
# Name:    foo
# Version: 0.1.0

Parameters:

  • fields (Hash, Array<(Object, Object)>)

    The fields to print.

Since:

  • 0.4.0



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/command_kit/printing/fields.rb', line 28

def print_fields(fields)
  max_length = 0

  fields = fields.map { |name,value|
    name       = name.to_s
    value      = value.to_s
    max_length = name.length if name.length > max_length

    [name, value]
  }

  fields.each do |name,value|
    first_line, *rest = value.to_s.lines(chomp: true)

    # print the first line with the header
    header = "#{name}:".ljust(max_length + 1)
    puts "#{header} #{first_line}"

    # indent and print the rest of the lines
    indent(max_length + 2) do
      rest.each do |line|
        puts line
      end
    end
  end

  return nil
end