View Source Want.Shape (want v2.0.0)

Provides macros for declaring an Ecto-like schema definition that can be used to cast incoming data. Most of the macro logic here was adapted from Ecto.Schema.

Summary

Functions

Cast incoming data based on a Shape definition.

Cast incoming data based on a Shape definition. Raises on error.

Cast a list of maps to a list of Shapes.

Cast a list of maps to a list of Shapes.

Define an embedded shape within a shape. Generates a nested module and registers a field of that module's type.

Define a field within a shape.

Determine whether the given module represents a shape.

Define a shape schema. Generates a struct definition for the current module that includes the data needed to correctly cast incoming JSON/map data into that struct, including field sourcing, type conversions, etc.

Define a shape schema. Generates a struct definition for the current module that includes the data needed to correctly cast incoming JSON/map data into that struct, including field sourcing, type conversions, etc.

Functions

@spec cast(module(), map()) :: {:ok, struct()} | {:error, reason :: term()}

Cast incoming data based on a Shape definition.

@spec cast(module(), map(), opts :: Keyword.t()) ::
  {:ok, struct()} | {:error, reason :: term()}
@spec cast!(module(), map()) :: struct()

Cast incoming data based on a Shape definition. Raises on error.

Link to this function

cast!(shape, data, opts)

View Source
@spec cast!(module(), map(), opts :: Keyword.t()) :: struct()
@spec cast_all(module(), [map()]) :: {:ok, [struct()]} | {:error, reason :: term()}

Cast a list of maps to a list of Shapes.

@spec cast_all!(module(), [map()]) :: [struct()]

Cast a list of maps to a list of Shapes.

Link to this macro

embeds(name, list)

View Source (macro)

Define an embedded shape within a shape. Generates a nested module and registers a field of that module's type.

Example

defmodule MyOrder do
  use Want.Shape

  shape do
    field   :id,      :integer
    embeds  :address do
      field :street, :string
      field :city,   :string
    end
  end
end
Link to this macro

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

View Source (macro)

Define a field within a shape.

@spec is_shape?(module()) :: boolean()

Determine whether the given module represents a shape.

Define a shape schema. Generates a struct definition for the current module that includes the data needed to correctly cast incoming JSON/map data into that struct, including field sourcing, type conversions, etc.

Link to this macro

shape(opts, list)

View Source (macro)

Define a shape schema. Generates a struct definition for the current module that includes the data needed to correctly cast incoming JSON/map data into that struct, including field sourcing, type conversions, etc.

Options

  • :transform - A function that accepts the generated shape struct and performs any transformations required. Called after a successful cast.