Module: CommandKit::Printing::Indent

Included in:
Fields, Lists, Tables
Defined in:
lib/command_kit/printing/indent.rb

Overview

Adds the ability to automatically indent all calls to puts.

Examples

include Printing::Indent

def run
  puts "regular output:"

  indent(4) do
    puts "indented output"
    puts "..."
  end

  puts "back to regular output"
end

Instance Method Summary collapse

Instance Method Details

#indent(n = 2) { ... } ⇒ Integer

Increases the indentation level by two, yields, then restores the indentation level.

Examples:

puts "values:"
indent do
  values.each do |key,value|
    puts "#{key}: #{value}"
  end
end
puts "Code:"
puts
puts "```"
indent(4) do
  code.each_line do |line|
    puts line
  end
end
puts "```"

Parameters:

  • n (Integer) (defaults to: 2)

    How much to increase the indentation level by.

Yields:

  • [] The given block will be called after the indentation level has been increased.

Returns:

  • (Integer)

    If no block is given, the indentation level will be returned.



68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/command_kit/printing/indent.rb', line 68

def indent(n=2)
  if block_given?
    original_indent = @indent

    begin
      @indent += n
      yield
    ensure
      @indent = original_indent
    end
  else
    @indent
  end
end

#initialize(**kwargs) ⇒ Object

Initializes the indentation level to zero.



27
28
29
30
31
# File 'lib/command_kit/printing/indent.rb', line 27

def initialize(**kwargs)
  @indent = 0

  super(**kwargs)
end

#puts(*lines) ⇒ Object

Indents and prints the lines to stdout.

Parameters:

  • lines (Array<String>)

    The lines to indent and print.



91
92
93
94
95
96
97
98
99
# File 'lib/command_kit/printing/indent.rb', line 91

def puts(*lines)
  if (@indent > 0 && !lines.empty?)
    padding = " " * @indent

    super(*lines.map { |line| "#{padding}#{line}" })
  else
    super(*lines)
  end
end