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

Casts and dumps a given struct 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 without the schema information.

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, even in the absence of schema information, 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

Functions

Invoked when attempting to cast this data structure to another type

Invoked when the data structure has not been cast along the way and must fallback to its database representation

Types

t :: term

Functions

cast(value, type)

Specs

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

Invoked when attempting to cast this data structure to another type.

dump(value)

Specs

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

Invoked when the data structure has not been cast along the way and must fallback to its database representation.