View Source CozyParams.Schema (cozy_params v0.2.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:
schema(do: block)
field(name, type, opts \\ [])
- available
opts
::default
:required
- default:false
- available
embeds_one(name, opts \\ [], do: block)
- available
opts
::required
- default:false
- available
embeds_one(name, schema, opts \\ [])
- available
opts
::required
- default:false
- available
embeds_many(name, opts \\ [], do: block)
- available
opts
::required
- default:false
- available
embeds_many(name, schema, opts \\ [])
- available
opts
::required
- default:false
- available
type
argument will be passed toEcto.Schema
, so it supports all the types supported byEcto.Schema
in theory. Read Types and casting section ofEcto.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:
changeset/2
which is overridable.from/1
/from/2
which will be called by high-level abstractions, such asCozyParams
,CozyParams.PhoenixController
.
You can specify the type of return value of from/2
:
PersonParams.from(%{}, type: :struct) # %PersonParams{}
PersonParams.from(%{}, type: :map) # %{}