Skip to content

Instantly share code, notes, and snippets.

@schrockwell
Last active October 19, 2021 12:21
Show Gist options
  • Save schrockwell/ef16f791bed458959919bd4908ea5d7c to your computer and use it in GitHub Desktop.
Save schrockwell/ef16f791bed458959919bd4908ea5d7c to your computer and use it in GitHub Desktop.
Ecto atom custom type
defmodule MyApp.Ecto.Atom do
@behaviour Ecto.Type
#
# BEHAVIOUR
#
def type, do: :string
def cast(value) when is_binary(value) or is_atom(value) do
{:ok, atomize(value)}
end
def load(string) when is_binary(string) do
{:ok, atomize(string)}
end
def dump(atom) when is_atom(atom) do
{:ok, stringify(atom)}
end
#
# PRIVATE
#
defp atomize(nil), do: nil
defp atomize(string) when is_binary(string), do: String.to_atom(string)
defp atomize(atom) when is_atom(atom), do: atom
defp stringify(nil), do: nil
defp stringify(string) when is_binary(string), do: string
defp stringify(atom) when is_atom(atom), do: Atom.to_string(atom)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment