class Fog::Kubevirt::Utils::UnitConverter
This class contains functions performing unit calculations. Originally implemented for manageiq-providers-kubevirt project
Constants
- SCALE_FACTORS
Scale factors associated to the different unit suffixes.
- VALUE_RE
Regular expression used to match values and to separate them into the numeric value and the optional unit suffix.
Public Class Methods
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.
@param value [String] The value to convert, with an optional unit suffix. @param to [Symbol] (:b) The name of the unit to convert to, for example `:gib`. @return [BigDecimal] The converted value.
# 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
Validates and extracts the numeric value and the unit
@param value [String] The value to validate with optional unit suffix. @return [MatchData] describing the match, or ValidationError is raised if no match.
# 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
Private Class Methods
Finds the scale factor that matches the given unit suffix.
@param sufix [Symbol, String] The unit suffix, as symbol or string. For example `MiB` or `:mib`. @return [Integer] The scale factor corresponding to that unit.
# File lib/fog/kubevirt/compute/utils/unit_converter.rb, line 105 def self.scale_factor(suffix) suffix = suffix.downcase.to_sym if suffix.kind_of?(String) factor = SCALE_FACTORS[suffix] raise ::Fog::Kubevirt::Errors::ValidationError, "The value '#{suffix}' isn't a valid unit suffix" unless factor factor end