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 custom(mod, name) :: %{
  :__struct__ => mod,
  :__type__ => t(name),
  optional(atom()) => any()
}
@type fun() :: (any() -> :ok | {:error, String.t()})
@type t() :: t(atom())
@type t(name) :: %Vx.Type{
  constraints: [Vx.Constraint.t()],
  fun: (... -> any()),
  name: name,
  of: [any()]
}

Functions

Link to this macro

__using__(name)

View Source (macro)

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
Link to this function

constrain(type, name, value \\ nil, fun)

View Source
@spec constrain(type, atom(), any(), Vx.Constraint.fun()) :: type
when type: t(atom()) | custom(module(), atom())

Adds a constraint to the type.

@spec constraints(type) :: [Vx.Constraint.t()]
when type: t(atom()) | custom(module(), atom())

Returns the constraints of the type.

Link to this function

constraints(type, name)

View Source (since 0.4.0)
@spec constraints(type, atom()) :: [Vx.Constraint.t()]
when type: t(atom()) | custom(module(), atom())

Returns the constraints of the type with the given name.

Link to this function

new(name, of \\ [], fun)

View Source
@spec new(name, [any()], (... -> any())) :: t(name) when name: atom()

Creates a new type.