Skip to content

Commit

Permalink
Add Decimal support to Money.Ecto.Composite.Type
Browse files Browse the repository at this point in the history
- Implement support for `Decimal` in the `load/1` function of `Money.Ecto.Composite.Type`.
  • Loading branch information
Eduardo López committed Nov 28, 2024
1 parent 3ebda47 commit a1624a2
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
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)}

@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

0 comments on commit a1624a2

Please sign in to comment.