Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.