Skip to content

Instantly share code, notes, and snippets.

@evadne
Created November 11, 2018 01:06
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 evadne/9cc86197d3b44c94f46ad000ca7816e3 to your computer and use it in GitHub Desktop.
Save evadne/9cc86197d3b44c94f46ad000ca7816e3 to your computer and use it in GitHub Desktop.
Environment Variable based Config Provider
defmodule Huddle.Environment do
use GenServer
@config_entries [
{:huddle_web, HuddleWeb.Endpoint, ~w(http port)a, {:system, "PORT"}}
]
def start_link(args) do
GenServer.start_link(__MODULE__, args)
end
def init(args) do
with :ok <- configure(@config_entries) do
{:ok, args}
end
end
defp configure([]), do: :ok
defp configure([h|t]) do
with :ok <- configure_entry(h) do
configure(t)
end
end
defp configure_entry({app, key, path, source}) do
with \
from_env <- Application.get_env(app, key),
{:ok, value} <- resolve_source(source),
to_env <- put_in(from_env, path, value),
:ok <- Application.put_env(app, key, to_env, persistent: true)
do
:ok
end
end
defp resolve_source({:system, envar}) do
case System.get_env(envar) do
nil -> {:error, {:missing_envar, envar}}
"" -> {:error, {:missing_envar, envar}}
value -> {:ok, value}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment