For loading a JSON into structs using Ecto-Schema I need some custom EctoTypes.
They are all the same: one of a list of atoms. So I tried to encapsulate that into a behaviour but I get an error I do not understand:
defmodule EctoAtomId do
defmacro __using__(opts) do
quote location: :keep, bind_quoted: [opts: opts] do
use Ecto.Type
@behaviour EctoAtomId
@ids Keyword.fetch!(opts, :ids)
@ids_as_string for(id <- @ids, do: Atom.to_string(id))
@type_name Keyword.fetch!(opts, :type_name)
def type, do: @type_name
def cast(data) when data in @ids_as_string, do: {:ok, String.to_exisiting_atom(data)}
def cast(data) when data in @ids, do: {:ok, data}
def cast(), do: :error
def load(data) when data in @ids_as_string, do: {:ok, String.to_exisiting_atom(data)}
def load(_), :error
def dump(id), do: {:ok, Atom.to_string(atom)}
end
end
end
when using it in this module:
defmodule Job do
use EctoAtomId, ids: [:job_mechanic, :job_doc, :job_programmer], type_name: :job
end
I get this error:
== Compilation error in file lib/job.ex ==
** (CompileError) lib/ecto_atom.ex:4: missing :do option in "def"
lib/job.ex:4: (module)