Skip to content

Instantly share code, notes, and snippets.

@bitwalker
Created June 6, 2016 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitwalker/bd596946d0dbdea2454ad10d7111a1bf to your computer and use it in GitHub Desktop.
Save bitwalker/bd596946d0dbdea2454ad10d7111a1bf to your computer and use it in GitHub Desktop.
A nice config wrapper which allows using the {:system, "VAR"} convention comfortably
defmodule Config do
@moduledoc """
This module handles fetching values from the config with some additional niceties
"""
@doc """
Fetches a value from the config, or from the environment if {:system, "VAR"}
is provided.
An optional default value can be provided if desired.
## Example
iex> {test_var, expected_value} = System.get_env |> Enum.take(1) |> List.first
...> Application.put_env(:myapp, :test_var, {:system, test_var})
...> ^expected_value = #{__MODULE__}.get(:myapp, :test_var)
...> :ok
:ok
iex> Application.put_env(:myapp, :test_var2, 1)
...> 1 = #{__MODULE__}.get(:myapp, :test_var2)
1
iex> :default = #{__MODULE__}.get(:myapp, :missing_var, :default)
:default
"""
@spec get(atom, atom, term | nil) :: term
def get(app, key, default \\ nil) when is_atom(app) and is_atom(key) do
case Application.get_env(app, key) do
{:system, env_var} ->
case System.get_env(env_var) do
nil -> default
val -> val
end
{:system, env_var, preconfigured_default} ->
case System.get_env(env_var) do
nil -> preconfigured_default
val -> val
end
nil ->
default
val ->
val
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment