DEV Community

Cover image for Taming data with Ecto.Enum and Ecto.Type
Herminio Torres
Herminio Torres

Posted on

Taming data with Ecto.Enum and Ecto.Type

Let's take advantage of Ecto.Enum and Ecto.Type.

The schema:

defmodule Blog.Category do
  use Blog.Schema

  schema "categories" do
    field(:name, Ecto.Enum, [:til, :elixir, :ecto])
  end
end
Enter fullscreen mode Exit fullscreen mode

Divide & Conquer with Reflections and Ecto.Type.load/3:

iex> type = Blog.Category.__schema__(:type, :name)
{:parameterized, Ecto.Enum,
 %{
   mappings: [til: "til", elixir: "elixir", ecto: "ecto"],
   on_cast: %{"til" => :til, "elixir" => :elixir, "ecto" => :ecto},
   on_dump: %{til: "til", elixir: "elixir", ecto: "ecto"},
   on_load: %{"til" => :til, "elixir" => :elixir, "ecto" => :ecto},
   type: :string
 }}
iex> Ecto.Type.load(type, "unknown")
:error
iex> Ecto.Type.load(type, "ecto")
{:ok, :ecto}
iex> Ecto.Type.load(type, :ecto)
:error
Enter fullscreen mode Exit fullscreen mode

In the meantime:

iex> Ecto.Enum.values(Blog.Category, :name)
[:til, :elixir, :ecto]
iex> Ecto.Enum.dump_values(Blog.Category, :name)
["til", "elixir", "ecto"]
iex> Ecto.Enum.mappings(Blog.Category, :name)
[til: "til", elixir: "elixir", ecto: "ecto"]
Enter fullscreen mode Exit fullscreen mode

Also, another great resource from German Velasco where he wrote Richer domain types with Ecto custom types

Happy Hacking!

Top comments (0)