From d271446d4b8613f40f0ea3d0e0a645d44b451ed8 Mon Sep 17 00:00:00 2001 From: Ilja Tkachuk Date: Thu, 12 Dec 2019 14:40:39 +0200 Subject: [PATCH] allow empty enums --- lib/ecto_enum/postgres/use.ex | 6 +++++- lib/ecto_enum/typespec.ex | 3 +++ lib/ecto_enum/use.ex | 6 +++++- test/ecto_enum_test.exs | 12 ++++++++++++ 4 files changed, 25 insertions(+), 2 deletions(-) diff --git a/lib/ecto_enum/postgres/use.ex b/lib/ecto_enum/postgres/use.ex index 4676668..a9c9c2d 100644 --- a/lib/ecto_enum/postgres/use.ex +++ b/lib/ecto_enum/postgres/use.ex @@ -9,7 +9,9 @@ defmodule EctoEnum.Postgres.Use do @behaviour Ecto.Type - @type t :: unquote(typespec) + if typespec do + @type t :: unquote(typespec) + end enums = input[:enums] valid_values = enums ++ Enum.map(enums, &Atom.to_string/1) @@ -49,6 +51,8 @@ defmodule EctoEnum.Postgres.Use do def load(unquote(string)), do: {:ok, unquote(atom)} end + def load(_), do: :error + def valid_value?(value) do Enum.member?(unquote(valid_values), value) end diff --git a/lib/ecto_enum/typespec.ex b/lib/ecto_enum/typespec.ex index cb72d4e..ad7f5b1 100644 --- a/lib/ecto_enum/typespec.ex +++ b/lib/ecto_enum/typespec.ex @@ -1,6 +1,9 @@ defmodule EctoEnum.Typespec do @moduledoc "Helper for generating enum typespecs" + def make([]), do: nil + def make(%{} = x) when map_size(x) == 0, do: nil + def make(enums) do enums |> Enum.reverse() diff --git a/lib/ecto_enum/use.ex b/lib/ecto_enum/use.ex index 292da2a..a407827 100644 --- a/lib/ecto_enum/use.ex +++ b/lib/ecto_enum/use.ex @@ -9,7 +9,9 @@ defmodule EctoEnum.Use do @behaviour Ecto.Type - @type t :: unquote(typespec) + if typespec do + @type t :: unquote(typespec) + end keys = Keyword.keys(opts) string_keys = Enum.map(keys, &Atom.to_string/1) @@ -52,6 +54,8 @@ defmodule EctoEnum.Use do def load(unquote(value)), do: {:ok, unquote(key)} end + def load(_), do: :error + def valid_value?(value) do Enum.member?(@valid_values, value) end diff --git a/test/ecto_enum_test.exs b/test/ecto_enum_test.exs index 0a7f10b..dcd9f46 100644 --- a/test/ecto_enum_test.exs +++ b/test/ecto_enum_test.exs @@ -287,6 +287,18 @@ defmodule EctoEnumTest do ]} end + test "allow empty enums" do + require EctoEnum + + EctoEnum.defenum( + Void, + :void, + [] + ) + + assert Void.__enums__() == [] + end + def custom_error_msg(value) do "Value `#{inspect(value)}` is not a valid enum for `EctoEnumTest.StatusEnum`." <> " Valid enums are `#{inspect(StatusEnum.__valid_values__())}`"