Class: Vagrant::Util::Numeric
- Inherits:
-
Object
- Object
- Vagrant::Util::Numeric
- Defined in:
- lib/vagrant/util/numeric.rb
Constant Summary collapse
- KILOBYTE =
Authors Note: This conversion has been borrowed from the ActiveSupport Numeric class Conversion helper constants
1024
- MEGABYTE =
KILOBYTE * 1024
- GIGABYTE =
MEGABYTE * 1024
- TERABYTE =
GIGABYTE * 1024
- PETABYTE =
TERABYTE * 1024
- EXABYTE =
PETABYTE * 1024
- BYTES_CONVERSION_MAP =
{KB: KILOBYTE, MB: MEGABYTE, GB: GIGABYTE, TB: TERABYTE, PB: PETABYTE, EB: EXABYTE}
- SHORTHAND_MATCH_REGEX =
Regex borrowed from the vagrant-disksize config class
/^(?<number>[0-9]+)\s?(?<unit>KB|MB|GB|TB)?$/
- LOGGER =
Log4r::Logger.new("vagrant::util::numeric")
Class Method Summary collapse
-
.bytes_to_megabytes(bytes) ⇒ Integer
Rounds actual value to two decimal places.
-
.bytes_to_string(bytes) ⇒ String
Convert bytes to a user friendly string representation.
-
.reset! ⇒ Object
Reset the cached values for platform.
-
.string_to_bytes(str) ⇒ Integer?
A helper that converts a shortcut string to its bytes representation.
Class Method Details
.bytes_to_megabytes(bytes) ⇒ Integer
Rounds actual value to two decimal places
79 80 81 |
# File 'lib/vagrant/util/numeric.rb', line 79 def bytes_to_megabytes(bytes) (bytes / MEGABYTE.to_f).round(2) end |
.bytes_to_string(bytes) ⇒ String
Convert bytes to a user friendly string representation
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/vagrant/util/numeric.rb', line 59 def bytes_to_string(bytes) # We want to locate the size that will return the # smallest whole value number BYTES_CONVERSION_MAP.sort { |a, b| b.last <=> a.last }.each do |suffix, size| val = bytes.to_f / size next if val < 1 val = sprintf("%.2f", val) val.slice!(-1, 1) while val.end_with?("0") val.slice!(-1, 1) if val.end_with?(".") return "#{val}#{suffix}" end "#{bytes} byte#{"s" if bytes > 1}" end |
.reset! ⇒ Object
Reset the cached values for platform. This is not considered a public API and should only be used for testing.
86 87 88 |
# File 'lib/vagrant/util/numeric.rb', line 86 def reset! instance_variables.each(&method(:remove_instance_variable)) end |
.string_to_bytes(str) ⇒ Integer?
A helper that converts a shortcut string to its bytes representation.
The expected format of str
is essentially: "XX
is shorthand for KB, MB, GB, TB, PB, or EB. For example, 50 megabytes:
str = "50MB"
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/vagrant/util/numeric.rb', line 36 def string_to_bytes(str) bytes = nil str = str.to_s.strip matches = SHORTHAND_MATCH_REGEX.match(str) if matches number = matches[:number].to_i unit = matches[:unit].to_sym if BYTES_CONVERSION_MAP.key?(unit) bytes = number * BYTES_CONVERSION_MAP[unit] else LOGGER.error("An invalid unit or format was given, string_to_bytes cannot convert #{str}") end end bytes end |