View Source Skema.Schema (Skema v0.1.0)

Borrow from https://github.com/ejpcmac/typed_struct/blob/main/lib/typed_struct.ex

Summary

Functions

Defines a typed struct.

Defines a field in a typed struct.

Functions

Link to this macro

def_schema(module \\ nil, list)

View Source (macro)

Defines a typed struct.

Inside a def_schema block, each field is defined through the field/2 macro.

Examples

defmodule MyStruct do
  use Skema.Schema

  def_schema do
    field :field_one, :string
    field :field_two, :integer, required: true
    field :field_three, :boolean, required: true
    field :field_four, :atom, default: :hey
    field :update_time, :naive_datetime, default: &NaiveDateTime.utc_now/0
  end
end

You can create the struct in a submodule instead:

defmodule MyModule do
  use Skema.Schema

  def_schema Comment do
    field :user_id, :integer, required: true
    field :content, :string, required: true
  end

  def_schema Post do
    field :field_one, :string
    field :field_two, :integer, required: true
    field :field_three, :boolean, required: true
    field :field_four, :string, default: "hello"
    field :update_time, :naive_datetime, default: &NaiveDateTime.utc_now/0
    field :comment, Comment, required: true
  end
end

MyModule.Post.cast(%{field_two: 1, field_three: true, comment: %{user_id: 1, content: "hello"}})
Link to this macro

field(name, type, opts \\ [])

View Source (macro)

Defines a field in a typed struct.

Example

# A field named :example of type String.t()
field :example, String.t()

Options

  • default - sets the default value for the field
  • enforce - if set to true, enforces the field and makes its type non-nullable