View Source CozyEnv (cozy_env v0.2.0)

Helpers for handling OS environment variables.

It helps to provide:

  • user-friendly error messages
  • ...

Summary

Functions

Gets the value of the given environment variable, and casts it into given type.

Gets the value of the given environment variable, and casts it into given type.

Types

@type data_type() :: :boolean | :integer | :float | :string | :atom
@type option() :: {:message, String.t()}
@type options() :: [option()]
@type result() :: boolean() | integer() | float() | String.t() | atom()

Functions

@spec fetch_env!(String.t()) :: String.t()
Link to this function

fetch_env!(varname, type)

View Source
@spec fetch_env!(String.t(), data_type()) :: result()
@spec fetch_env!(String.t(), options()) :: String.t()
Link to this function

fetch_env!(varname, type, opts)

View Source
@spec fetch_env!(String.t(), data_type(), options()) :: result()

Gets the value of the given environment variable, and casts it into given type.

If the environment variable is not set, raises an error.

Examples

iex> CozyEnv.fetch_env!("NOT_SET", :boolean)
** (CozyEnv.EnvError) environment variable NOT_SET is missing
    (cozy_env) lib/cozy_env.ex:134: CozyEnv.fetch_env!/3
    iex:1: (file)

# export PHX_SERVER=true
iex> CozyEnv.fetch_env!("PHX_SERVER", :boolean)
true

# export DB_POOL_SIZE=10
iex> CozyEnv.fetch_env!("DB_POOL_SIZE", :integer)
10

# export PERCENT=0.95
iex> CozyEnv.fetch_env!("PERCENT", :float)
0.95

# export USER=billy
iex> CozyEnv.fetch_env!("USER", :string)
"billy"

# export USER=billy
iex> CozyEnv.fetch_env!("USER", :atom)
:billy
@spec get_env(String.t()) :: String.t()
@spec get_env(String.t(), data_type()) :: result()

Gets the value of the given environment variable, and casts it into given type.

If the environment variable is not set, returns nil.

Examples

iex> CozyEnv.get_env("NOT_SET", :boolean)
nil

# export PHX_SERVER=true
iex> CozyEnv.get_env("PHX_SERVER", :boolean)
true

# export DB_POOL_SIZE=10
iex> CozyEnv.get_env("DB_POOL_SIZE", :integer)
10

# export PERCENT=0.95
iex> CozyEnv.get_env("PERCENT", :float)
0.95

# export USER=billy
iex> CozyEnv.get_env("USER", :string)
"billy"

# export USER=billy
iex> CozyEnv.get_env("USER", :atom)
:billy