Skip to content

Commit

Permalink
Do not absorb type atoms
Browse files Browse the repository at this point in the history
  • Loading branch information
mathieuprog committed Sep 23, 2022
1 parent cda67e1 commit 81f8fe9
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
11 changes: 7 additions & 4 deletions lib/polymorphic_embed.ex
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ defmodule PolymorphicEmbed do
|> Enum.map(fn
{type_name, type_opts} ->
%{
type: to_string(type_name),
type: type_name,
module: Keyword.fetch!(type_opts, :module),
identify_by_fields:
type_opts |> Keyword.get(:identify_by_fields, []) |> Enum.map(&to_string/1)
Expand Down Expand Up @@ -361,7 +361,6 @@ defmodule PolymorphicEmbed do
defp do_get_polymorphic_type(module, types_metadata) do
get_metadata_for_module(module, types_metadata)
|> Map.fetch!(:type)
|> String.to_atom()
end

@doc """
Expand All @@ -373,18 +372,22 @@ defmodule PolymorphicEmbed do
"""
def types(schema, field) do
%{types_metadata: types_metadata} = get_field_options(schema, field)
Enum.map(types_metadata, &String.to_existing_atom(&1.type))
Enum.map(types_metadata, &(&1.type))
end

defp get_metadata_for_module(module, types_metadata) do
Enum.find(types_metadata, &(module == &1.module))
end

defp get_metadata_for_type(type, types_metadata) do
type = to_string(type)
type = maybe_to_existing_atom(type)
Enum.find(types_metadata, &(type == &1.type))
end

defp maybe_to_existing_atom(value) when is_atom(value), do: value

defp maybe_to_existing_atom(value), do: String.to_existing_atom(value)

defp get_field_options(schema, field) do
try do
schema.__schema__(:type, field)
Expand Down
21 changes: 21 additions & 0 deletions test/polymorphic_embed_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -2087,6 +2087,27 @@ defmodule PolymorphicEmbedTest do
text_input(f, :text)
end)
end

# https://github.com/mathieuprog/polymorphic_embed/issues/59#issuecomment-1255774332
test "make sure that we do not 'absorb' atoms" do
opts = [
types: [
sms: PolymorphicEmbed.Channel.SMS,
email: [
module: PolymorphicEmbed.Channel.Email,
identify_by_fields: [:address, :confirmed]
]
],
on_replace: :update,
type_field: :my_type_field
]

PolymorphicEmbed.init(opts)
|> Map.fetch!(:types_metadata)
|> Enum.each(fn %{type: type} ->
assert is_atom(type)
end)
end
end

describe "types/2" do
Expand Down

0 comments on commit 81f8fe9

Please sign in to comment.