diff --git a/lib/money/ecto/composite_type.ex b/lib/money/ecto/composite_type.ex index 6b418b4..ffbfdca 100644 --- a/lib/money/ecto/composite_type.ex +++ b/lib/money/ecto/composite_type.ex @@ -29,10 +29,9 @@ if Code.ensure_loaded?(Ecto.Type) do @spec type() :: :money_with_currency def type, do: :money_with_currency - @spec load({integer(), atom() | String.t()}) :: {:ok, Money.t()} - def load({amount, currency}) do - {:ok, Money.new(amount, currency)} - end + @spec load({integer() | Decimal.t(), atom() | String.t()}) :: {:ok, Money.t()} + def load({amount, currency}) when is_integer(amount), do: {:ok, Money.new(amount, currency)} + def load({%Decimal{} = amount, currency}), do: {:ok, amount |> Decimal.to_integer() |> Money.new(currency)} @spec dump(any()) :: :error | {:ok, {integer(), String.t()}} def dump(%Money{} = money), do: {:ok, {money.amount, to_string(money.currency)}} diff --git a/test/money/ecto/composite_type_test.exs b/test/money/ecto/composite_type_test.exs index 48c5f04..4ac45f4 100644 --- a/test/money/ecto/composite_type_test.exs +++ b/test/money/ecto/composite_type_test.exs @@ -33,6 +33,11 @@ defmodule Money.Ecto.Composite.TypeTest do assert Type.load({100, "JPY"}) == {:ok, Money.new(100, :JPY)} end + test "load/1 Tuple with `Decimal.new/1`: {Decimal.new/1, currency}" do + assert Type.load({Decimal.new("1"), "USD"}) == {:ok, Money.new(1, :USD)} + assert Type.load({Decimal.new("1000"), "MXN"}) == {:ok, Money.new(1000, :MXN)} + end + test "dump/1 Money" do assert Type.dump(Money.new(1, :USD)) == {:ok, {1, "USD"}} assert Type.dump(Money.new(100, :JPY)) == {:ok, {100, "JPY"}}