Module: WhittakerTech::Midas::Coin::Converter

Included in:
WhittakerTech::Midas::Coin
Defined in:
app/models/whittaker_tech/midas/coin/converter.rb

Overview

Converter implements cross-currency conversion for Coin, backed by a provider-agnostic adapter (default: Coin::Converter::BankProvider wrapping Money.default_bank). Every successful conversion writes an immutable WhittakerTech::Midas::Exchange audit row, which owns both a copy of the source value (from) and the converted result (to).

Since:

  • 0.3.0

Defined Under Namespace

Classes: BankProvider

Instance Method Summary collapse

Instance Method Details

#convert_to(currency_code, at: nil, using: nil) ⇒ Coin Also known as: exchange_to

Converts this Coin to another currency.

The receiver does not need to be persisted — it's only ever read, never mutated or reassigned. The result is a brand-new, persisted Coin owned by a newly created Exchange audit row (not linked back to this Coin's own resource).

Parameters:

  • currency_code (String)

    target ISO 4217 currency code

  • at (Time, nil) (defaults to: nil)

    rate timestamp; nil (default) means "now". A non-nil value requires using: to supply a provider implementing #exchange_at.

  • using (Object, Money::Bank::Base, nil) (defaults to: nil)

    provider override; any object responding to #exchange(money, currency_code) and #name, or a raw Money::Bank::* instance (auto-wrapped in BankProvider)

Returns:

  • (Coin)

    the persisted to Coin (the converted result), owned by the newly created Exchange audit row

Raises:

  • (ArgumentError)

    if at is given and the resolved provider has no #exchange_at

Since:

  • 0.3.0



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'app/models/whittaker_tech/midas/coin/converter.rb', line 29

def convert_to(currency_code, at: nil, using: nil)
  provider = resolve_provider(using)
  iso = currency_code.to_s.strip.upcase

  if currency_minor.zero?
    converted_cents = 0
    rate = BigDecimal(0)
  else
    converted = fetch_rate(provider, iso, at)
    converted_cents = converted.cents
    rate = BigDecimal(converted_cents) / BigDecimal(currency_minor)
  end

  persist_conversion(provider, iso, at, converted_cents, rate)
end