Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions lib/money/ecto/composite_type.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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)}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Decimal.to_integer is not a safe conversion


@spec dump(any()) :: :error | {:ok, {integer(), String.t()}}
def dump(%Money{} = money), do: {:ok, {money.amount, to_string(money.currency)}}
Expand Down
5 changes: 5 additions & 0 deletions test/money/ecto/composite_type_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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"}}
Expand Down