View Source CozyParams.Schema (cozy_params v0.1.0)

Provides macros for defining schemas which is used for casting and validating params.

Due to limitations of implementation, it's impossible to document every supported macros within @doc. Because of that, I will try to best to document them within @moduledoc.

available-macros

Available macros

CozyParams.Schema provides a subset of macros supported by Ecto, In addition, it makes some changes on embeds_one and embeds_many.

In a nutshell, all available macros are:

  1. schema(do: block)
  2. field(name, type, opts \\ [])
    • available opts:
      • :default
      • :required - default: false
  3. embeds_one(name, opts \\ [], do: block)
    • available opts:
      • :required - default: false
  4. embeds_one(name, schema, opts \\ [])
    • available opts:
      • :required - default: false
  5. embeds_many(name, opts \\ [], do: block)
    • available opts:
      • :required - default: false
  6. embeds_many(name, schema, opts \\ [])
    • available opts:
      • :required - default: false

type argument will be passed to Ecto.Schema, so it supports all the types supported by Ecto.Schema in theory. Read Types and casting section of Ecto.Schema to get more information.

examples

Examples

Define a schema contains embedded fields in inline syntax:

defmodule PersonParams do
  use CozyParams.Schema

  schema do
    field :name, :string, required: true
    field :age, :integer

    embeds_one :mate, required: true do
      field :name, :string, required: true
      field :age, :integer
    end

    embeds_many :pets do
      field :name, :string, required: true
      field :breed, :string
    end
  end
end

PersonParams.from(%{})

Define a schema contains embedded fields with extra modules:

defmodule PersonParams do
  use CozyParams.Schema

  defmodule Mate do
    use CozyParams.Schema

    schema do
      field :name, :string, required: true
      field :age, :integer
    end
  end

  defmodule Pet do
    use CozyParams.Schema

    schema do
      field :name, :string, required: true
      field :breed, :string
    end
  end

  schema do
    field :name, :string, required: true
    field :age, :integer
    embeds_one :mate, Mate, required: true
    embeds_many :pets, Pet
  end
end

PersonParams.from(%{})

about-the-generated-functions

About the generated functions

schema/1 will create 2 functions automatically:

  1. changeset/2 which is overridable.
  2. from/1 / from/2 which will be called by high-level abstractions, such as CozyParams, CozyParams.PhoenixController.

You can specify the type of return value of from/2:

PersonParams.from(%{}, type: :struct) # %PersonParams{}
PersonParams.from(%{}, type: :map)    # %{}

Link to this section Summary

Link to this section Functions

Link to this macro

schema(list)

View Source (since 0.1.0) (macro)