Class: String
- Inherits:
-
Object
- Object
- String
- Defined in:
- lib/wavefront-cli/string.rb
Overview
Extensions to the String class to help with formatting.
Instance Method Summary collapse
-
#cmd_fold(tw = TW, indent = 10) ⇒ Object
Fold long command lines.
-
#fold(tw = TW, indent = 10, prefix = '') ⇒ String
Fold long lines with a hanging indent.
-
#opt_fold(tw = TW, indent = 10) ⇒ String
Wrapper around #fold().
-
#scan_line(width) ⇒ Array
Original string chunked into an array width elements whose length < width.
- #to_seconds ⇒ Object
Instance Method Details
#cmd_fold(tw = TW, indent = 10) ⇒ Object
Fold long command lines. We can’t break on a space after an option or it confuses docopt.
10 11 12 13 14 |
# File 'lib/wavefront-cli/string.rb', line 10 def cmd_fold(tw = TW, indent = 10) #gsub(/\s(?=\w+\])/, '^').scan_line(tw - 8).join("\n" + ' ' * indent) gsub(/(-\w) /, "\\1^").scan_line(tw - 12).join("\n" + ' ' * indent) .tr('^', ' ') end |
#fold(tw = TW, indent = 10, prefix = '') ⇒ String
Fold long lines with a hanging indent. Originally a special case for option folding, now addded the prefix parameter to make it more general.
rubocop:disable Metrics/AbcSize
37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/wavefront-cli/string.rb', line 37 def fold(tw = TW, indent = 10, prefix = '') chunks = self.scan_line(tw - 8) line_1 = format("%s%s\n", prefix, chunks.shift) return line_1 if chunks.empty? rest = chunks.join(' ').scan_line(tw - indent - 5).map do |l| prefix + ' ' * indent + l end line_1 + rest.join("\n") + "\n" end |
#opt_fold(tw = TW, indent = 10) ⇒ String
Wrapper around #fold()
22 23 24 |
# File 'lib/wavefront-cli/string.rb', line 22 def opt_fold(tw = TW, indent = 10) fold(tw, indent, ' ') end |
#scan_line(width) ⇒ Array
Returns original string chunked into an array width elements whose length < width.
56 57 58 |
# File 'lib/wavefront-cli/string.rb', line 56 def scan_line(width) scan(/\S.{0,#{width}}\S(?=\s|$)|\S+/) end |
#to_seconds ⇒ Object
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
# File 'lib/wavefront-cli/string.rb', line 60 def to_seconds begin number, unit = self.match(/^(\d+)([smhdw])$/).captures rescue raise ArgumentError end factor = case unit when 's' 1 when 'm' 60 when 'h' 3600 when 'd' 86400 when 'w' 604800 else raise ArgumentError end number.to_i * factor end |