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, decimals: 2, separator: ".", unit_separator: "") ⇒ String

Convert value to bytes

Parameters:

  • value (Numeric)

    the value to convert to bytes

  • decimals (Integer) (defaults to: 2)

    the number of decimals parts

  • separator (String) (defaults to: ".")

    the separator to use for thousands in a number

  • unit_separator (String) (defaults to: "")

    the separtor to use between number and unit

Returns:

  • (String)


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

def to_bytes(value, decimals: 2, separator: ".", 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



46
47
48
49
# File 'lib/tty/progressbar/converter.rb', line 46

def to_seconds(seconds, precision: nil)
  precision ||= (seconds < 1 && !seconds.zero?) ? 5 : 2
  format "%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
33
34
# File 'lib/tty/progressbar/converter.rb', line 17

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

  if days > 0 # over 24 hours switch to days
    format("%dd%2dh%2dm", days, hours, minutes)
  elsif hours > 0
    format("%2dh%2dm", hours, minutes)
  elsif minutes > 0
    format("%2dm%2ds", minutes, seconds)
  else
    format("%2ds", seconds)
  end
end