Module: CLI::Kit::Util

Defined in:
lib/cli/kit/util.rb

Class Method Summary collapse

Class Method Details

.begin(&block_that_might_raise) ⇒ Object

Must call retry_after on the result in order to execute the block

Example usage:

CLI::Kit::Util.begin do

might_raise_if_costly_prep_not_done()

end.retry_after(ExpectedError) do

costly_prep()

end : [T] { -> T } -> Retrier



82
83
84
# File 'lib/cli/kit/util.rb', line 82

def begin(&block_that_might_raise)
  Retrier.new(block_that_might_raise)
end

.to_filesize(bytes, precision: 2, space: false) ⇒ Object

Converts an integer representing bytes into a human readable format

: (Integer bytes, ?precision: Integer, ?space: bool) -> String



13
14
15
# File 'lib/cli/kit/util.rb', line 13

def to_filesize(bytes, precision: 2, space: false)
  to_si_scale(bytes, 'B', precision: precision, space: space, factor: 1024)
end

.to_si_scale(number, unit = '', factor: 1000, precision: 2, space: false) ⇒ Object

Converts a number to a human readable format on the SI scale

: (Numeric number, ?String unit, ?factor: Integer, ?precision: Integer, ?space: bool) -> String

Raises:

  • (ArgumentError)


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
# File 'lib/cli/kit/util.rb', line 20

def to_si_scale(number, unit = '', factor: 1000, precision: 2, space: false)
  raise ArgumentError, 'factor should only be 1000 or 1024' unless [1000, 1024].include?(factor)

  small_scale = ['m', 'µ', 'n', 'p', 'f', 'a', 'z', 'y']
  big_scale = ['k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
  negative = number < 0
  number = number.abs.to_f

  if number == 0.0 || number.between?(1, factor)
    prefix = ''
    scale = 0
  else
    scale = Math.log(number, factor).floor
    if number < 1
      index = [-scale - 1, small_scale.length].min
      scale = -(index + 1)
      prefix = small_scale[index] #: as !nil
    else
      index = [scale - 1, big_scale.length].min
      scale = index + 1
      prefix = big_scale[index] #: as !nil
    end
  end

  divider = (factor**scale)
  fnum = (number / divider.to_f).round(precision)

  # Trim useless decimal
  fnum = fnum.to_i if (fnum.to_i.to_f * divider.to_f) == number

  fnum = -fnum if negative
  if space
    prefix = ' ' + prefix
  end

  "#{fnum}#{prefix}#{unit}"
end

.with_dir(dir, &block) ⇒ Object

Dir.chdir, when invoked in block form, complains when we call chdir again recursively. There’s no apparent good reason for this, so we simply implement our own block form of Dir.chdir here. : [T] (String dir) { -> T } -> T



62
63
64
65
66
67
68
69
70
# File 'lib/cli/kit/util.rb', line 62

def with_dir(dir, &block)
  prev = Dir.pwd
  begin
    Dir.chdir(dir)
    yield
  ensure
    Dir.chdir(prev)
  end
end