Class: Fog::Kubevirt::Utils::UnitConverter

Inherits:
Object
  • Object
show all
Defined in:
lib/fog/kubevirt/compute/utils/unit_converter.rb

Overview

This class contains functions performing unit calculations. Originally implemented for manageiq-providers-kubevirt project

Class Method Summary collapse

Class Method Details

.convert(value, to) ⇒ BigDecimal

Converts a value containing an optional unit to another unit. For example, if the value is ‘2 MiB` and the unit is `KiB` the result will be 2048.

Parameters:

  • value (String)

    The value to convert, with an optional unit suffix.

  • to (Symbol)

    (:b) The name of the unit to convert to, for example ‘:gib`.

Returns:

  • (BigDecimal)

    The converted value.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/fog/kubevirt/compute/utils/unit_converter.rb', line 18

def self.convert(value, to)
  # Return nil if no value is given:
  return nil unless value
  
  match = validate(value)
  value = match[:value]
  from = match[:suffix]
  
  # Convert the value from string to big decimal to make sure that we don't loose precission:
  value = BigDecimal(value)
  
  # Do the conversion:
  from_factor = scale_factor(from)
  to_factor = scale_factor(to)
  value * from_factor / to_factor
end

.validate(value) ⇒ MatchData

Validates and extracts the numeric value and the unit

Parameters:

  • value (String)

    The value to validate with optional unit suffix.

Returns:

  • (MatchData)

    describing the match, or ValidationError is raised if no match.

Raises:



41
42
43
44
45
46
# File 'lib/fog/kubevirt/compute/utils/unit_converter.rb', line 41

def self.validate(value)
  match = VALUE_RE.match(value)
  raise ::Fog::Kubevirt::Errors::ValidationError, "The value '#{value}' isn't a valid unit" unless match
  
  match
end