Module: Dolibarr::Coerce

Defined in:
lib/dolibarr/coerce.rb

Overview

Restler serialises every amount as a string ("8900.00000000"). This absorbs that quirk: it deep-walks a parsed response and turns money-typed string fields into BigDecimal (never Float — accounting arithmetic must stay exact). Detection is by key, not by value, so an all-digits identifier (a socid, a phone number) under a non-money key is never mistaken for an amount.

Constant Summary collapse

AMOUNT_KEY =

Keys whose value is a monetary amount: money-ish prefixes (total…, montant…, amount…, remain…, deposit…) and money-ish suffixes (…_ht, …_ttc, …_tva, …_vat, …_pu, …_localtax). Deliberately excludes paye/paid, which Dolibarr uses as 0/1 flags, not amounts.

/
  \A(?:total|montant|amount|remain|deposit)
  | _(?:ht|ttc|tva|vat|pu|localtax\d*)\z
/xi
NUMERIC =

A plain decimal string, optionally signed. Guards against coercing free text ("N/A", "") that Dolibarr sometimes returns in a money field.

/\A-?\d+(?:\.\d+)?\z/

Class Method Summary collapse

Class Method Details

.amounts(obj) ⇒ Object

Deep-walk obj, returning a copy with every money-keyed numeric string coerced to BigDecimal. Hashes and arrays are traversed; scalars pass through.

Parameters:

  • obj (Object)

    a parsed JSON value (Hash, Array, or scalar)

Returns:

  • (Object)

    the same shape with amounts coerced



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/dolibarr/coerce.rb', line 30

def self.amounts(obj)
  case obj
  when Array
    obj.map { |v| amounts(v) }
  when Hash
    obj.each_with_object({}) do |(key, value), out|
      out[key] = amount?(key, value) ? BigDecimal(value) : amounts(value)
    end
  else
    obj
  end
end