Current section
Files
Jump to
Current section
Files
lib/ecto_shortuuid/builder.ex
defmodule Ecto.ShortUUID.Builder do
defmacro __using__(opts) do
shortuuid_module = Keyword.get(opts, :shortuuid_module, ShortUUID)
quote do
alias Ecto.UUID
@behaviour Ecto.Type
@shortuuid_module unquote(shortuuid_module)
@type shortuuid :: binary
@type uuid :: binary
@impl true
def type, do: :uuid
@impl true
def cast(<<_::288>> = uuid) do
case UUID.cast(uuid) do
:error -> :error
{:ok, casted} -> @shortuuid_module.encode(casted)
end
end
@spec cast(shortuuid | uuid | any) :: {:ok, shortuuid} | :error
def cast(shortuuid) when is_binary(shortuuid) do
case @shortuuid_module.decode(shortuuid) do
{:ok, _} -> {:ok, shortuuid}
{:error, _} -> :error
end
end
def cast(_), do: :error
@impl true
def load(<<_::128>> = uuid) do
{:ok, @shortuuid_module.encode!(uuid)}
end
def load(_), do: :error
@impl true
def dump(string) when is_binary(string) do
# Try to decode as shortuuid first
case @shortuuid_module.decode(string) do
{:ok, uuid} -> {:ok, uuid}
:error ->
# If that fails, try as UUID string
try do
UUID.dump(string)
rescue
ArgumentError -> :error
end
end
end
def dump(_), do: :error
@impl true
def embed_as(_), do: :self
@impl true
def equal?(term1, term2), do: term1 == term2
def generate do
UUID.generate()
|> @shortuuid_module.encode()
end
def autogenerate, do: generate()
end
end
end