Last active
October 19, 2021 12:21
-
-
Save schrockwell/ef16f791bed458959919bd4908ea5d7c to your computer and use it in GitHub Desktop.
Ecto atom custom type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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