Class: Cri::StringFormatter
- Inherits:
-
Object
- Object
- Cri::StringFormatter
- Defined in:
- lib/cri/string_formatter.rb
Instance Method Summary collapse
-
#format_as_command(s, io) ⇒ String
The string, formatted to be used as the name of a command in the help.
-
#format_as_option(s, io) ⇒ String
The string, formatted to be used as an option definition of a command in the help.
-
#format_as_title(s, io) ⇒ String
The string, formatted to be used as a title in a section in the help.
-
#to_paragraphs(s) ⇒ Array<String>
Extracts individual paragraphs (separated by two newlines).
-
#wrap_and_indent(s, width, indentation, first_line_already_indented = false) ⇒ String
Word-wraps and indents the string.
Instance Method Details
#format_as_command(s, io) ⇒ String
Returns The string, formatted to be used as the name of a command in the help
91 92 93 94 95 96 97 |
# File 'lib/cri/string_formatter.rb', line 91 def format_as_command(s, io) if Cri::Platform.color?(io) s.green else s end end |
#format_as_option(s, io) ⇒ String
Returns The string, formatted to be used as an option definition of a command in the help
103 104 105 106 107 108 109 |
# File 'lib/cri/string_formatter.rb', line 103 def format_as_option(s, io) if Cri::Platform.color?(io) s.yellow else s end end |
#format_as_title(s, io) ⇒ String
Returns The string, formatted to be used as a title in a section in the help
79 80 81 82 83 84 85 |
# File 'lib/cri/string_formatter.rb', line 79 def format_as_title(s, io) if Cri::Platform.color?(io) s.upcase.red.bold else s.upcase end end |
#to_paragraphs(s) ⇒ Array<String>
Extracts individual paragraphs (separated by two newlines).
10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/cri/string_formatter.rb', line 10 def to_paragraphs(s) lines = s.scan(/([^\n]+\n|[^\n]*$)/).map { |l| l[0].strip } paragraphs = [[]] lines.each do |line| if line.empty? paragraphs << [] else paragraphs.last << line end end paragraphs.reject(&:empty?).map { |p| p.join(' ') } end |
#wrap_and_indent(s, width, indentation, first_line_already_indented = false) ⇒ String
Word-wraps and indents the string.
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 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/cri/string_formatter.rb', line 39 def wrap_and_indent(s, width, indentation, first_line_already_indented = false) indented_width = width - indentation indent = ' ' * indentation # Split into paragraphs paragraphs = to_paragraphs(s) # Wrap and indent each paragraph text = paragraphs.map do |paragraph| # Initialize lines = [] line = '' # Split into words paragraph.split(/\s/).each do |word| # Begin new line if it's too long if (line + ' ' + word).length >= indented_width lines << line line = '' end # Add word to line line += (line == '' ? '' : ' ') + word end lines << line # Join lines lines.map { |l| indent + l }.join("\n") end.join("\n\n") if first_line_already_indented text[indentation..-1] else text end end |