Nvir.Cast (Nvir v0.13.1)

View Source

Collection of casters for environment variables.

Summary

Functions

Casts the given value to the desired type.

Types

caster()

@type caster() ::
  :string
  | :string?
  | :string!
  | :atom
  | :atom?
  | :atom!
  | :existing_atom
  | :existing_atom?
  | :existing_atom!
  | :boolean
  | :boolean!
  | :boolean?
  | :integer!
  | :integer?
  | :integer
  | :float!
  | :float?
  | :float
  | (term() -> result())

result()

@type result() ::
  {:ok, term()} | {:error, String.t()} | {:error, :empty} | {:error, :bad_cast}

Functions

cast(value, caster)

@spec cast(term(), caster()) :: result()
@spec cast(String.t(), caster()) :: result()

Casts the given value to the desired type.

Environment variables are always defined as a string. Thus, the cast/2 function will only accept strings for the value argument.

Accepts a built-in caster or a custom function returning {:ok, value} or {:error, String.t()}. You may as well directly return an error tuple from a recursive cast/2 call.

Built-in casters

String Casters

CasterDescription
:stringReturns the value as-is.
:string?Converts empty strings to nil.
:string!Raises for empty strings.

Boolean Casters

CasterDescription
:boolean"false", "0" and empty strings become false, any other value is true. Case insensitive. It is recommended to use :boolean! instead.
:boolean!Accepts only "true", "false", "1", and "0". Case insensitive.

Number Casters

CasterDescription
:integer!Strict integer parsing.
:integer?Like :integer! but empty strings becomes nil.
:float!Strict float parsing.
:float?Like :float! but empty strings becomes nil.

Atom Casters

CasterDescription
:atomConverts the value to an atom. Use the :existing_atom variants when possible.
:atom?Like :atom but empty strings becomes nil.
:atom!Like :atom but rejects empty strings.
:existing_atomConverts to existing atom only, raises otherwise.
:existing_atom?Like :existing_atom but empty strings becomes nil.
:existing_atom!Like :existing_atom but rejects empty strings.

Note that using :existing_atom with empty strings will not raise an exception because the :"" atom is valid and is generally defined by the system on boot.

Deprecated casters

Those exist for legacy reasons and should be avoided. They will trigger a runtime warning when used.

In some languages, using null where a number is expected will cast the value to a default type value, generally 0 and +0.0 for integers and floats. This behaviour does not exist in Elixir so casters for such types behave the same with-or-without the ! suffix. This means :integer and :float will raise for empty strings.

CasterDescription
:boolean?Same as :boolean. ⚠️ Returns false instead of nil for empty strings.
:integerSame as :integer!.
:floatSame as :float!.