Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Add Ecto.Type compatibility #66

@tleef

Description

@tleef

This may be a separate module.

The basic idea add a way for a Z.Struct to also be an Ecto.Type so that you can marshal to and from PostgreSQL composite types.

For example given the following Z.Struct

defmodule Money do
  use Z.Struct
  use Z.Ecto.Type, type: :money_with_currency

  schema do
    field :amount, :integer, required: true
    field :currency, :atom, default: :USD, required: true, parse: true, enum: [:USD]
  end
end

generate the following code

use Ecto.Type

def type, do: :money_with_currency

def load({amount, currency}) do
  Money.new(amount: amount, currency: currency)
end

def dump(%Money{} = money), do: {:ok, {money.amount, to_string(money.currency)}}
def dump(_), do: :error

def cast(money) do
  Money.validate(money, cast: true, required: true)
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions