Skip to content

Instantly share code, notes, and snippets.

@adamgavlak
Created February 7, 2018 23:52
Show Gist options
  • Save adamgavlak/897f69355647ea1135752730535f8b6c to your computer and use it in GitHub Desktop.
Save adamgavlak/897f69355647ea1135752730535f8b6c to your computer and use it in GitHub Desktop.
defmodule PrefixID do
@doc """
Custom Ecto.Type use macro
Example:
use PrefixID, prefix: "secret_key"
After this, the Ecto type will have
all features defined below.
"""
defmacro __using__(opts) do
prefix = opts[:prefix] || "test"
quote bind_quoted: [prefix: prefix] do
@behaviour Ecto.Type
def type, do: :string
def cast(string) when is_binary(string) do
{:ok, string}
end
defp prepared_prefix do
unquote(prefix) <> "_"
end
def autogenerate() do
prepared_prefix() <> Random.base58()
end
def cast(_), do: :error
def dump(string) when is_binary(string) do
{:ok, string}
end
def load(string) when is_binary(string) do
{:ok, string}
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment