From 2c17e97144e8367ba414567edffbef8081c9777f Mon Sep 17 00:00:00 2001 From: Andrew Glassman Date: Thu, 16 May 2024 03:11:32 -0500 Subject: [PATCH] Support Decimal result in Ecto load. (#220) --- lib/money/ecto/amount_type.ex | 1 + test/money/ecto/amount_type_test.exs | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/lib/money/ecto/amount_type.ex b/lib/money/ecto/amount_type.ex index 8d6e432..1ca412f 100644 --- a/lib/money/ecto/amount_type.ex +++ b/lib/money/ecto/amount_type.ex @@ -67,6 +67,7 @@ if Code.ensure_loaded?(Ecto.Type) do @spec load(integer()) :: {:ok, Money.t()} def load(int) when is_integer(int), do: {:ok, Money.new(int)} + def load(%Decimal{} = decimal), do: {:ok, decimal |> Decimal.to_integer() |> Money.new()} @spec dump(integer() | Money.t()) :: {:ok, integer()} def dump(int) when is_integer(int), do: {:ok, int} diff --git a/test/money/ecto/amount_type_test.exs b/test/money/ecto/amount_type_test.exs index a62375e..1d576f9 100644 --- a/test/money/ecto/amount_type_test.exs +++ b/test/money/ecto/amount_type_test.exs @@ -56,6 +56,10 @@ defmodule Money.Ecto.Amount.TypeTest do assert Type.load(1000) == {:ok, Money.new(1000, :GBP)} end + test "load/1 decimal" do + assert Type.load(Decimal.new("1000")) == {:ok, Money.new(1000, :GBP)} + end + test "dump/1 integer" do assert Type.dump(1000) == {:ok, 1000} end