From 81f8fe939ae5aa22005aa8879775a7b477e52f36 Mon Sep 17 00:00:00 2001 From: mathieuprog <5883963+mathieuprog@users.noreply.github.com> Date: Fri, 23 Sep 2022 16:57:22 +0200 Subject: [PATCH] Do not absorb type atoms --- lib/polymorphic_embed.ex | 11 +++++++---- test/polymorphic_embed_test.exs | 21 +++++++++++++++++++++ 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/lib/polymorphic_embed.ex b/lib/polymorphic_embed.ex index 119163d..0bcbc46 100644 --- a/lib/polymorphic_embed.ex +++ b/lib/polymorphic_embed.ex @@ -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) @@ -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 """ @@ -373,7 +372,7 @@ 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 @@ -381,10 +380,14 @@ defmodule PolymorphicEmbed do 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) diff --git a/test/polymorphic_embed_test.exs b/test/polymorphic_embed_test.exs index 7caa92e..2f21b84 100644 --- a/test/polymorphic_embed_test.exs +++ b/test/polymorphic_embed_test.exs @@ -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