View Source Want.List (want v2.0.0)

Manages conversions to and from lists.

Summary

Functions

Cast an input into a list. By default this function will simply break up the input into list elements, but further casting and validation of elements can be performed by providing an element option. The separator used to split the list defaults to the comma character and this can be controlled using the separator option.

Callback implementation for Want.Type.cast/2.

Types

@type element() :: any()
@type result() :: {:ok, [element()]} | {:error, binary()}

Functions

Cast an input into a list. By default this function will simply break up the input into list elements, but further casting and validation of elements can be performed by providing an element option. The separator used to split the list defaults to the comma character and this can be controlled using the separator option.

Options

  • :separator - Determines the character(s) used to separate list items. Defaults to the comma character.
  • :element - Provides the ability to further control how list elements are cast and validated. Similar to the map and keywords functions, accepts a keyword list with its own :type field and validation options.
  • :on_error - Controls behaviour when an element cast fails. :drop (default) silently removes the failed element. :error halts and returns the first error.
  • :min - Minimum allowable number of elements in the resulting list.
  • :max - Maximum allowable number of elements in the resulting list.

Examples

iex> Want.List.cast("1")
{:ok, ["1"]}

iex> Want.List.cast("1", element: [type: :integer])
{:ok, [1]}

iex> Want.List.cast("1,2,3,4", element: [type: :integer])
{:ok, [1, 2, 3, 4]}

iex> Want.List.cast("1:2:3:4", separator: ":", element: [type: :integer])
{:ok, [1, 2, 3, 4]}

iex> Want.List.cast("hello:world", separator: ":", element: [type: :enum, valid: [:hello, :world]])
{:ok, [:hello, :world]}

iex> Want.List.cast("hello:world", separator: ":", element: [type: :enum, valid: [:hello]])
{:ok, [:hello]}

iex> Want.List.cast("hello:world", separator: ":", element: [type: :enum, valid: [:hello]], on_error: :error)
{:error, "\"world\" did not match any valid enum values."}

iex> Want.List.cast("a,b,c", min: 2)
{:ok, ["a", "b", "c"]}

iex> Want.List.cast("a", min: 2)
{:error, "List length below minimum of 2."}

iex> Want.List.cast("a,b,c,d,e", max: 3)
{:error, "List length exceeds maximum of 3."}
@spec cast(value :: any(), opts :: Keyword.t()) :: result()

Callback implementation for Want.Type.cast/2.