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
- #unit_factor(unit) ⇒ 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 |
# File 'lib/wavefront-cli/string.rb', line 10 def cmd_fold(tw = TW, indent = 10) 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.
35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/wavefront-cli/string.rb', line 35 def fold(tw = TW, indent = 10, prefix = '') chunks = scan_line(tw - 8) first_line = format("%s%s\n", prefix, chunks.shift) return first_line if chunks.empty? rest = chunks.join(' ').scan_line(tw - indent - 5).map do |l| prefix + ' ' * indent + l end first_line + rest.join("\n") + "\n" end |
#opt_fold(tw = TW, indent = 10) ⇒ String
Wrapper around #fold()
21 22 23 |
# File 'lib/wavefront-cli/string.rb', line 21 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.
54 55 56 |
# File 'lib/wavefront-cli/string.rb', line 54 def scan_line(width) scan(/\S.{0,#{width}}\S(?=\s|$)|\S+/) end |
#to_seconds ⇒ Object
58 59 60 61 62 63 64 65 66 |
# File 'lib/wavefront-cli/string.rb', line 58 def to_seconds begin number, unit = match(/^(\d+)([smhdw])$/).captures rescue NoMethodError raise ArgumentError end number.to_i * unit_factor(unit.to_sym) end |
#unit_factor(unit) ⇒ Object
68 69 70 71 |
# File 'lib/wavefront-cli/string.rb', line 68 def unit_factor(unit) factors = { s: 1, m: 60, h: 3600, d: 86_400, w: 604_800 } factors[unit] || 1 end |