Rewrite Ecto module implementation

Replace Isn.Base and its gigantic `__using__` method with a simple for
comprehension to generate all of the separate modules instead.
This commit is contained in:
Martin Frost 2015-10-02 20:24:50 +02:00
parent b69b2b4190
commit 489a461b34
1 changed files with 26 additions and 57 deletions

View File

@ -55,35 +55,14 @@ defmodule Isn do
do: binary do: binary
end end
defmodule Isn.Base do for module <- ~w(ISBN ISMN ISSN ISBN13 ISMN13 ISSN13 UPC EAN13) do
@moduledoc """ module_name = Module.concat([Isn, module])
Base module for Isn custom ecto types. ecto_type = module |> String.downcase |> String.to_atom
""" defmodule module_name do
@doc """
Set up basic functionality for an Isn type.
This extends the calling module by defining implementations for
* type/0
* blank?/0
* cast/1
* load/1
* dump/1
"""
defmacro __using__(_opts) do
ecto_type = __CALLER__.module
|> Atom.to_string
|> String.replace(~r(.+\.), "")
isn_type = ecto_type
|> String.downcase
|> String.to_atom
quote bind_quoted: [isn_type: isn_type, ecto_type: ecto_type] do
@behaviour Ecto.Type @behaviour Ecto.Type
@moduledoc """ @moduledoc """
Definition for the #{isn_type} module. Definition for the #{module_name} module.
How to use this in an Ecto.Model How to use this in an Ecto.Model
@ -91,13 +70,13 @@ defmodule Isn.Base do
use MyApp.Web, :model use MyApp.Web, :model
schema "books" do schema "books" do
field :#{isn_type}, Isn.#{ecto_type} field :#{module_name}, Isn.#{ecto_type}
# other fields # other fields
end end
end end
""" """
def type, do: unquote(isn_type) def type, do: unquote(ecto_type)
defdelegate blank?, to: Ecto.Type defdelegate blank?, to: Ecto.Type
@ -108,14 +87,4 @@ defmodule Isn.Base do
def dump(isn), do: {:ok, to_string(isn)} def dump(isn), do: {:ok, to_string(isn)}
end end
end
end end
defmodule Isn.ISBN, do: use(Isn.Base)
defmodule Isn.ISMN, do: use(Isn.Base)
defmodule Isn.ISSN, do: use(Isn.Base)
defmodule Isn.ISBN13, do: use(Isn.Base)
defmodule Isn.ISMN13, do: use(Isn.Base)
defmodule Isn.ISSN13, do: use(Isn.Base)
defmodule Isn.UPC, do: use(Isn.Base)
defmodule Isn.EAN13, do: use(Isn.Base)