ValidatedStruct

TestsHex version badge

ValidatedStruct is a library to define struct that come with built-in validation based on specs.

ValidatedStruct is a plugin for type struct.

Installation

If available in Hex, the package can be installed by adding validated_struct to your list of dependencies in mix.exs:

def deps do
  [
    {:validated_struct, "~> 0.0.3"}
  ]
end

Documentation can be generated with ExDoc and published on HexDocs. Once published, the docs can be found at https://hexdocs.pm/validated_struct.

Example

defmodule Money do
  use ValidatedStruct

  validatedstruct do
      field :amount, non_neg_integer()
      field :currency, :eur | :usd
  end
end

The above code generates functions called make and update that can be used to create and update structs with validation:

{:ok, money} = Money.make(amount: 10, currency: :eur)
{:ok, updated_money} = Money.update(acount: 11)

{:error, _} = Money.make(amount: 10, currency: :cad)
{:error, _} = Money.make(amount: "10", currency: :usd)

Fields in validated structs are always enforced.

Overview

Hot code reloading in releases

ValidatedStruct heavily relies on debug information, which is usually stripped in production code.

You have to add strip_beams: [keep: ["Dbgi"]] in your release config in root > mix.exs > &project/0 > releases > <release_name>

Generators

There is a library, that adds stream data generators to validated struct. It can be found at hex.pm.