Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/wavefront-cli/string.rb

Overview

Extensions to the String class to help with formatting.

Instance Method Summary collapse

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.

Parameters:

  • tw (Integer) (defaults to: TW)

    terminal width

  • indent (Integer) (defaults to: 10)

    size of hanging indent, in chars



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.

Parameters:

  • tw (Integer) (defaults to: TW)

    terminal width

  • indent (Integer) (defaults to: 10)

    size of hanging indent, in chars

  • prefix (String) (defaults to: '')

    prepended to every line

Returns:

  • (String)

    the folded line



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()

Parameters:

  • tw (Integer) (defaults to: TW)

    width of terminal, in chars

  • indent (Integer) (defaults to: 10)

    hanging indent of following lines

Returns:

  • (String)

    folded and indented string



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.

Parameters:

  • width (Integer)

    length of longest string (width of terminal less some margin)

Returns:

  • (Array)

    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_secondsObject



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