Ecto v2.0.0-beta.1 Ecto.DataType protocol

Casts a given data type into an Ecto.Type.

While Ecto.Type allows developers to cast/load/dump any value from the storage into the struct based on the schema, Ecto.DataType allows developers to convert existing data types into existing Ecto types, be them primitive or custom.

For example, Ecto.Date is a custom type, represented by the %Ecto.Date{} struct that can be used in place of Ecto’s primitive :date type. Therefore, we need to tell Ecto how to convert %Ecto.Date{} into :date and such is done with the Ecto.DataType protocol:

defimpl Ecto.DataType, for: Ecto.Date do
  # Dumps to the default representation. In this case, :date.
  def dump(value) do
    cast(value, :date)
  end

  # Implement any other desired casting rule.
  def cast(%Ecto.Date{day: day, month: month, year: year}, :date) do
    {:ok, {year, month, day}}
  end

  def cast(_, _) do
    :error
  end
end

Summary

Types

t :: term

Functions

cast(value, type)

Specs

cast(term, Ecto.Type.t) :: {:ok, term} | :error
dump(value)

Specs

dump(term) :: {:ok, term} | :error