Skip to content

Commit

Permalink
Bugfix: {Currency.Type.dump/1} missing ISO string support
Browse files Browse the repository at this point in the history
The callback 'cast/1' is only called when loading native types from the
database for some reason, what's counter-intuitive IMO.

I did check Ecto's docs and it states that it's 'dump/1's reponsability
to validate and convert the given value to a native time, that's why
I'm considering this a bugfix.

See {https://hexdocs.pm/ecto/Ecto.Type.html\#c:dump/1}.
  • Loading branch information
rwillians committed Mar 20, 2023
1 parent fb7cbfe commit f1b5505
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 4 deletions.
7 changes: 3 additions & 4 deletions lib/money/ecto/currency_type.ex
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ if Code.ensure_loaded?(Ecto.Type) do
@spec type :: :string
def type, do: :string

@spec cast(Money.t() | String.t()) :: {:ok, atom()}
@spec cast(Money.t() | String.t() | atom()) :: {:ok, atom()}
def cast(val)

def cast(%Money{currency: currency}), do: {:ok, currency}
Expand All @@ -49,8 +49,7 @@ if Code.ensure_loaded?(Ecto.Type) do
@spec load(String.t()) :: {:ok, atom()}
def load(str) when is_binary(str), do: {:ok, Currency.to_atom(str)}

@spec dump(atom()) :: {:ok, String.t()}
def dump(atom) when is_atom(atom), do: {:ok, Atom.to_string(atom)}
def dump(_), do: :error
@spec dump(Money.t() | String.t() | atom()) :: {:ok, String.t()}
def dump(val), do: with({:ok, atom} <- cast(val), do: {:ok, Atom.to_string(atom)})
end
end
4 changes: 4 additions & 0 deletions test/money/ecto/currency_type_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ defmodule Money.Ecto.Currency.TypeTest do
assert Type.dump(:CHF) == {:ok, "CHF"}
end

test "dump/1 string" do
assert Type.dump("CHF") == {:ok, "CHF"}
end

test "dump/1 other" do
assert Type.dump({:a, :b}) == :error
end
Expand Down

0 comments on commit f1b5505

Please sign in to comment.