Skip to content

Commit c1ced8a

Browse files
authored
Update handle_value to only convert values when the value has implemented the Enumerable protocol (#104)
Earlier, I opened https://github.com/sobolevn/recase/pull/97/files because passing a DateTime value to the converter would fail, since it passed the is_map check, but would not work when passed to Enum; I fixed it by hardcoding a new pattern-matched function against DateTimes, and early returning the datetime. However, I now need the same functionality, but for Decimal, which does not exist (and doesn't need to) in this lib. Unfortunately, is_map(%Decimal{}) also returns true, and then fails when passed to Enum. I think the best solution is to check if the Enumerable protocol is implemented, which may determine if the value can be passed to the next check.
1 parent be78a03 commit c1ced8a

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

lib/recase/utils/enumerable.ex

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -41,15 +41,16 @@ defmodule Recase.Enumerable do
4141
|> Enum.map(fn value -> handle_value(value, fun, &convert_keys/2) end)
4242
end
4343

44-
defp handle_value(%DateTime{} = value, _fun, _converter), do: value
45-
46-
defp handle_value(value, fun, converter)
47-
when is_map(value) or is_list(value) do
48-
converter.(value, fun)
44+
defp handle_value(value, fun, converter) do
45+
case Enumerable.impl_for(value) do
46+
nil ->
47+
value
48+
49+
_ ->
50+
converter.(value, fun)
51+
end
4952
end
5053

51-
defp handle_value(value, _, _), do: value
52-
5354
defp cast_string(value) when is_binary(value), do: value
5455

5556
defp cast_string(value) when is_atom(value), do: Atom.to_string(value)

0 commit comments

Comments
 (0)