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.



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

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

    begin
      @indent += n
      @indent_padding << (' ' * n)
      yield
    ensure
      @indent_padding.slice!(original_indent,n)
      @indent = original_indent
    end
  else
    @indent
  end
end

#initialize(**kwargs) ⇒ Object

Initializes the indentation level to zero.



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

def initialize(**kwargs)
  @indent = 0
  @indent_padding = String.new

  super(**kwargs)
end

#puts(*lines) ⇒ Object

Indents and prints the lines to stdout.

Parameters:

  • lines (Array<String>)

    The lines to indent and print.



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

def puts(*lines)
  if (@indent > 0 && !lines.empty?)
    super(*lines.map { |line| "#{@indent_padding}#{line}" })
  else
    super(*lines)
  end
end