Module: TTY::ProgressBar::Converter

Defined in:
lib/tty/progressbar/converter.rb

Overview

Responsible for converting values to different formats

Constant Summary collapse

HOURSECONDS =
3600
BYTE_UNITS =
%w(b kb mb gb tb pb eb).freeze

Class Method Summary collapse

Class Method Details

.to_bytes(value, options = {}) ⇒ String

Convert value to bytes

Parameters:

  • value (Numeric)

    the value to convert to bytes

  • options (Hash[Symbol]) (defaults to: {})
  • [Integer] (Hash)

    a customizable set of options

  • [String] (Hash)

    a customizable set of options

Returns:

  • (String)

67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/tty/progressbar/converter.rb', line 67

def to_bytes(value, options = {})
  decimals       = options.fetch(:decimals) { 2 }
  separator      = options.fetch(:separator) { '.' }
  unit_separator = options.fetch(:unit_separator) { '' }

  base    = 1024
  pattern = "%.#{decimals}f"

  unit = BYTE_UNITS.find.with_index { |_, i| value < base ** (i + 1) }

  if value < base
    formatted_value = value.to_i.to_s
  else
    value_to_size = value / (base ** BYTE_UNITS.index(unit)).to_f
    formatted_value = format(pattern, value_to_size)
  end

  formatted_value.gsub(/\./, separator) + unit_separator + unit.to_s.upcase
end

.to_seconds(seconds, precision = nil) ⇒ String

Convert seconds to set precision

Parameters:

  • seconds (Numeric)

    the seconds to convert

Returns:

  • (String)

    the formatted result


44
45
46
47
# File 'lib/tty/progressbar/converter.rb', line 44

def to_seconds(seconds, precision = nil)
  precision ||= (seconds < 1 && !seconds.zero?) ? 5 : 2
  sprintf "%5.#{precision}f", seconds
end

.to_time(seconds) ⇒ Object

Convert seconds to time notation

Parameters:

  • seconds (Numeric)

    the seconds to convert to time


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/tty/progressbar/converter.rb', line 17

def to_time(seconds)
  hours = (seconds / HOURSECONDS.to_f).floor
  seconds -= hours * HOURSECONDS
  minutes = (seconds / 60).floor
  seconds -= minutes * 60

  if hours > 99
    sprintf('%dh', hours)
  elsif hours > 0
    sprintf('%2dh%2dm', hours, minutes)
  elsif minutes > 0
    sprintf('%2dm%2ds', minutes, seconds)
  else
    sprintf('%2ds', seconds)
  end
end