Class: Cats::Core::UnitConversion

Inherits:
ApplicationRecord show all
Defined in:
app/models/cats/core/unit_conversion.rb

Class Method Summary collapse

Class Method Details

.convert(from, to, value) ⇒ Object

Raises:

  • (StandardError)


14
15
16
17
18
19
20
21
22
23
24
25
# File 'app/models/cats/core/unit_conversion.rb', line 14

def self.convert(from, to, value)
  return value if from == to

  conversion = find_by(from: from, to: to)
  return (value * conversion.factor).round(2) if conversion

  # Check if there is reverse conversion entry defined
  conversion = find_by(from: to, to: from)
  raise(StandardError, "Conversion factor between #{from.abbreviation} and #{to.abbreviation} not found.") unless conversion

  (value / conversion.factor).round(2)
end

.harmonized_total(list, unit) ⇒ Object

This function calculates the sum of quantities of a list of objects with quantities and different units into one. The list can be a list of hub authorizations, RHN requests, dispatch plan items, etc … This method assumes that quantity is represented by the attribute quantity and unit of measure is represented by the attribute unit for each object in the object list. If that is not true then one should create those two attributes as aliases in the respective models.



34
35
36
37
38
# File 'app/models/cats/core/unit_conversion.rb', line 34

def self.harmonized_total(list, unit)
  list.inject(0) do |res, obj|
    res + UnitConversion.convert(obj.unit, unit, obj.quantity)
  end
end