Created
February 7, 2018 23:52
-
-
Save adamgavlak/897f69355647ea1135752730535f8b6c to your computer and use it in GitHub Desktop.
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 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