Skip to content

Commit

Permalink
Merge pull request #49 from OnigiriJack/add-types-function
Browse files Browse the repository at this point in the history
Add types/2 function
  • Loading branch information
mathieuprog authored Feb 4, 2022
2 parents 376ff6e + b931e7e commit 73e2d89
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/polymorphic_embed.ex
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,18 @@ defmodule PolymorphicEmbed do
|> String.to_atom()
end

@doc """
Returns the possible types for a given schema and field
you can call `types/2` like this:
PolymorphicEmbed.types(MySchema, :contexts)
#=> [:location, :age, :device]
"""
def types(schema, field) do
%{types_metadata: types_metadata} = get_field_options(schema, field)
Enum.map(types_metadata, &String.to_existing_atom(&1.type))
end

defp get_metadata_for_module(module, types_metadata) do
Enum.find(types_metadata, &(module == &1.module))
end
Expand Down
7 changes: 7 additions & 0 deletions test/polymorphic_embed_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -1597,6 +1597,13 @@ defmodule PolymorphicEmbedTest do
end
end

describe "types/2" do
test "returns the types for a polymoprhic embed field" do
assert PolymorphicEmbed.types(PolymorphicEmbed.Reminder, :channel) ==
[:sms, :email]
end
end

describe "get_polymorphic_module/3" do
test "returns the module for a type" do
assert PolymorphicEmbed.get_polymorphic_module(PolymorphicEmbed.Reminder, :channel, :sms) ==
Expand Down

0 comments on commit 73e2d89

Please sign in to comment.