Skip to content

Instantly share code, notes, and snippets.

@churcho
Forked from hipertracker/.env
Created March 12, 2019 16:05
Show Gist options
  • Save churcho/4f243db7873306727ef5b53319ea2296 to your computer and use it in GitHub Desktop.
Save churcho/4f243db7873306727ef5b53319ea2296 to your computer and use it in GitHub Desktop.
Dynamic database configuration in Phoenix
[default]
DB_NAME=mydb
DB_PASSWORD=mypass
DB_USERNAME=myuser
defmodule MyApp.Repo do
use Ecto.Repo,
otp_app: :my_app,
adapter: Ecto.Adapters.Postgres
@doc """
In the production mode you cannot run ConfigParser.parse_file(".env") or Mix.env()
So to detect the environment mode put a flag to config/prod.exs:
config :my_app, MyApp.Repo, env: :prod
"""
def init(_, config) do
if config[:env] == :prod do
{:ok, config}
else
{:ok, inject_env(config)}
end
end
defp inject_env(config) do
config
|> Enum.map(fn item ->
case ConfigParser.parse_file(".env") do
{:ok, %{"default" => conf}} -> modify_config(conf, item)
_ -> item
end
end)
end
defp modify_config(conf, item) do
case item do
{:username, nil} -> {:username, conf["DB_USERNAME"]}
{:password, nil} -> {:password, conf["DB_PASSWORD"]}
{:database, nil} -> {:database, conf["DB_NAME"]}
_ -> item
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment