Class: Peddler::Money

Inherits:
Object
  • Object
show all
Defined in:
lib/peddler/money.rb

Overview

Coerces Amazon SP-API monetary values to Money objects

Class Method Summary collapse

Class Method Details

.parse(value) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/peddler/money.rb', line 11

def parse(value)
  return unless value

  amount = value["Amount"] || value["amount"] || value["value"]
  currency = value["CurrencyCode"] || value["currencyCode"]

  return unless amount && currency

  # The Money gem expects amounts in the smallest unit (e.g., cents for USD)
  #
  # We need to check the currency's subunit_to_unit to handle this correctly:
  # - For currencies like USD: multiply by 100
  # - For JPY: use as-is
  subunit_to_unit = ::Money::Currency.new(currency).subunit_to_unit
  if subunit_to_unit == 1
    ::Money.new(amount.to_i, currency)
  else
    fractional = (amount.to_f * subunit_to_unit).round
    ::Money.new(fractional, currency)
  end
end