Skip to content

Commit

Permalink
Merge pull request #164 from danschultzer/handle-digital-token-conver…
Browse files Browse the repository at this point in the history
…sion

Support digital token for currency conversion
  • Loading branch information
kipcole9 committed Feb 29, 2024
2 parents f81dd0e + da0d0a5 commit 6e4ea40
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 10 deletions.
22 changes: 12 additions & 10 deletions lib/money.ex
Expand Up @@ -1813,22 +1813,22 @@ defmodule Money do
{:ok, money}
end

def to_currency(%Money{} = money, to_currency, %{} = rates)
when is_binary(to_currency) do
with {:ok, currency_code} <- validate_currency(to_currency) do
to_currency(money, currency_code, rates)
end
end

def to_currency(%Money{currency: from_currency, amount: amount} = money, to_currency, rates)
when is_atom(to_currency) and is_map(rates) do
when is_atom(to_currency) or is_digital_token(to_currency) and is_map(rates) do
with {:ok, to_currency_code} <- validate_currency(to_currency),
{:ok, cross_rate} <- cross_rate(from_currency, to_currency_code, rates) do
{:ok, cross_rate} <- cross_rate(from_currency, to_currency_code, rates) do
converted_amount = Decimal.mult(amount, cross_rate)
{:ok, %{money | currency: to_currency, amount: converted_amount}}
end
end

def to_currency(%Money{} = money, to_currency, %{} = rates)
when is_binary(to_currency) do
with {:ok, currency_code} <- validate_currency(to_currency) do
to_currency(money, currency_code, rates)
end
end

@doc """
Convert `money` from one currency to another and raises on error
Expand Down Expand Up @@ -2433,8 +2433,10 @@ defmodule Money do
end

defp get_rate(currency, rates) do
keys = is_atom(currency) && [currency, Atom.to_string(currency)] || [currency]

rates
|> Map.take([currency, Atom.to_string(currency)])
|> Map.take(keys)
|> Map.values()
|> case do
[rate] ->
Expand Down
6 changes: 6 additions & 0 deletions test/money_test.exs
Expand Up @@ -428,6 +428,12 @@ defmodule MoneyTest do
assert Money.to_currency(Money.new(:USD, 100), "USD", rates) == {:ok, Money.new(:USD, 100)}
end

test "money conversion with digital_token" do
rates = %{:USD => Decimal.new(50_000), "4H95J0R2X" => Decimal.new(1)}
assert Money.to_currency(Money.new(:USD, 50_000), "4H95J0R2X", rates) == {:ok, Money.new("4H95J0R2X", "1.00000")}
assert Money.to_currency(Money.new("4H95J0R2X", 1), :USD, rates) == {:ok, Money.new(:USD, 50_000)}
end

test "money to_string" do
assert Money.to_string(Money.new(:USD, 100)) == {:ok, "$100.00"}
end
Expand Down

0 comments on commit 6e4ea40

Please sign in to comment.