Class: MmTool::OutputHelper

Inherits:
Object
  • Object
show all
Defined in:
lib/mm_tool/output_helper.rb

Class Method Summary collapse

Class Method Details

.console_widthObject


Gather the basic dimensions required for output. We’ll support a minimum width of 60, which is reasonable for any modern console, and allows enough room for fairly long argument examples. If STDOUT is not to a console, then adjust to 80 columns.




88
89
90
# File 'lib/mm_tool/output_helper.rb', line 88

def self.console_width
  $stdout.tty? ? [TTY::Screen.width, 60].max : 80
end

.hanging_string(string:, hang: 0, margin: 78) ⇒ Object


Return a string: with a hanging indent of hang: and a right margin of margin:.




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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/mm_tool/output_helper.rb', line 16

def self.hanging_string( string:, hang: 0, margin: 78 )
  indent_spaces = " " * hang
  result = []

  # Each individual paragraph should end with two newlines; therefore convert
  # individual newlines into spaces, and break the paragraphs into a split.
  string.gsub(/\n\n/, "\f").gsub(/\n/, " ").split(/\f/).each do |line|

    buffer = ''
    line.split(/\s/).each do |word|

      word = ' ' if word.length == 0

      len_buffer = buffer.gsub(/\e\[([;\d]+)?m/, '').length

      if len_buffer == 0 || buffer[-1] == ' '
        added_word = word
      else
        added_word = ' ' + word
      end

      len_word = added_word.gsub(/\e\[([;\d]+)?m/, '').length

      width = result.count == 0 ? margin : margin - hang

      if len_buffer + len_word <= width
        buffer = buffer + added_word
      else
        if result.count == 0
          result << buffer + "\n"
        else
          result << indent_spaces + buffer + "\n"
        end
        buffer = word
      end

    end # line

    if result.count == 0
      result << buffer + "\n\n"
    else
      result << indent_spaces + buffer + "\n\n"
    end

  end

  result.join[0...-1]
end

Displays an error message and returns from subroutine.




68
69
70
71
# File 'lib/mm_tool/output_helper.rb', line 68

def self.print_error(message)
  width = [TTY::Screen.width, 61].max - 1
  STDERR.puts self.hanging_string(string: message, hang: 3, margin: width)
end

Displays an error message and exits the program.




76
77
78
79
# File 'lib/mm_tool/output_helper.rb', line 76

def self.print_error_and_exit(message)
  self.print_error(message)
  exit 1
end