· 7 years ago · Feb 20, 2018, 06:32 PM
1defmodule PrefixID do
2
3 @doc """
4 Custom Ecto.Type use macro
5
6 Example:
7
8 use PrefixID, prefix: "secret_key"
9
10 After this, the Ecto type will have
11 all features defined below.
12 """
13 defmacro __using__(opts) do
14 prefix = opts[:prefix] || "test"
15
16 quote bind_quoted: [prefix: prefix] do
17 @behaviour Ecto.Type
18
19 def type, do: :string
20
21 def cast(string) when is_binary(string) do
22 {:ok, string}
23 end
24
25 defp prepared_prefix do
26 unquote(prefix) <> "_"
27 end
28
29 def autogenerate() do
30 prepared_prefix() <> Random.base58()
31 end
32
33 def cast(_), do: :error
34
35 def dump(string) when is_binary(string) do
36 {:ok, string}
37 end
38
39 def load(string) when is_binary(string) do
40 {:ok, string}
41 end
42 end
43 end
44end