View Source Vx.Type (Vx v0.4.0)
A basic type that implements the Vx.Validatable
protocol and allows adding
constraints to the type definition.
Summary
Functions
Turns a module into a custom type. It automatically implements the
Vx.Validatable
and Vx.Inspectable
protocols for the newly created type and
allows easily chaining constraints on your type.
Adds a constraint to the type.
Returns the constraints of the type.
Returns the constraints of the type with the given name.
Creates a new type.
Types
@type t(name) :: %Vx.Type{ constraints: [Vx.Constraint.t()], fun: (... -> any()), name: name, of: [any()] }
Functions
Turns a module into a custom type. It automatically implements the
Vx.Validatable
and Vx.Inspectable
protocols for the newly created type and
allows easily chaining constraints on your type.
Example
defmodule MyType do
use Vx.Type, :my_type
# The type constructor
@spec t() :: t
def t do
new(fn value ->
if my_type_is_valid?(value) do
:ok
else
{:error, "my type is not valid"}
end
end)
end
# A function that adds a constraint to a type
@spec foo(t) :: t
def foo(%__MODULE__{} = type \\ t()) do
constrain(schema, :my_constraint, fn value ->
if value < 123, do: :ok, else: {:error, "must be less than 123"}
end)
end
# ...
end
@spec constrain(type, atom(), any(), Vx.Constraint.fun()) :: type when type: t(atom()) | custom(module(), atom())
Adds a constraint to the type.
Returns the constraints of the type.
@spec constraints(type, atom()) :: [Vx.Constraint.t()] when type: t(atom()) | custom(module(), atom())
Returns the constraints of the type with the given name.
Creates a new type.