Bunch v0.3.0 Bunch.Config View Source

A bunch of helpers for parsing and validating configurations.

Link to this section Summary

Functions

Parses config according to fields_specs

Link to this section Functions

Link to this function

parse(config, fields_specs) View Source
parse(
  config :: Keyword.t(v),
  fields_specs ::
    Keyword.t(
      validate:
        (v | any() -> Bunch.Type.try_t() | boolean())
        | (v | any(), config_map -> Bunch.Type.try_t() | boolean()),
      in: [v],
      default: v,
      require_if: (config_map -> boolean())
    )
) :: Bunch.Type.try_t(config_map)
when config_map: %{optional(atom()) => v}, v: any()

Parses config according to fields_specs.

fields_specs consist of constraints on each field. Supported constraints are:

  • validate - function determining if field's value is correct
  • in - enumerable containing all valid values
  • default - value returned if a field is not found in config
  • require_if - function determining if a field is required basing on previous fields' values

Examples

iex> Bunch.Config.parse([a: 1, b: 2], a: [validate: & &1 > 0], b: [in: -2..2])
{:ok, %{a: 1, b: 2}}
iex> Bunch.Config.parse([a: 1, b: 4], a: [validate: & &1 > 0], b: [in: -2..2])
{:error, {:config_field, {:invalid_value, [key: :b, value: 4, reason: {:not_in, -2..2}]}}}
iex> Bunch.Config.parse(
...> [a: 1, b: 2],
...> a: [validate: & &1 > 0],
...> b: [in: -2..2],
...> c: [default: 5]
...> )
{:ok, %{a: 1, b: 2, c: 5}}
iex> Bunch.Config.parse(
...> [a: 1, b: 2],
...> a: [validate: & &1 > 0],
...> b: [in: -2..2],
...> c: [require_if: & &1.a == &1.b]
...> )
{:ok, %{a: 1, b: 2}}
iex> Bunch.Config.parse(
...> [a: 1, b: 1],
...> a: [validate: & &1 > 0],
...> b: [in: -2..2],
...> c: [require_if: & &1.a == &1.b]
...> )
{:error, {:config_field, {:key_not_found, :c}}}