Class: Cats::Core::ValidationUtil

Inherits:
Object
  • Object
show all
Defined in:
app/utils/cats/core/validation_util.rb

Class Method Summary collapse

Class Method Details

.validate_quantity(obj, parent_attr, relation, error_key, quantity_attribs = nil, unit_attribs = nil) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'app/utils/cats/core/validation_util.rb', line 4

def self.validate_quantity(obj, parent_attr, relation, error_key, quantity_attribs = nil, unit_attribs = nil)
  parent = obj.send(parent_attr)
  quantity = quantity_attribs ? Util.send_chain(parent, quantity_attribs) : parent.quantity
  unit = unit_attribs ? Util.send_chain(parent, unit_attribs) : parent.unit
  total = UnitConversion.convert(unit, obj.unit, quantity)
  used = UnitConversion.harmonized_total(relation, obj.unit)
  used -= obj.quantity_was if obj.quantity_was

  remaining = total - used
  return unless obj.quantity > remaining

  error = "exceeds #{error_key} quantity. Maximum allowed is #{remaining} #{obj.unit.abbreviation}"
  obj.errors.add(:quantity, error)
end