Cony v0.2.3 Cony View Source
Provides macros for defining a config module that uses environment variables.
Here is an example implementation with Ecto
:
# ~/.bash_profile
MY_APP_REPO_USERNAME="root"
MY_APP_REPO_PASSWORD="s3cr3t"
MY_APP_REPO_DATABASE="my_app"
MY_APP_REPO_HOSTNAME="localhost"
defmodule MyApp.RepoConfig do
import Cony
config env_prefix: "my_app_repo_" do
add :username, :string
add :password, :string
add :database, :string
add :hostname, :string, default: "localhost"
end
end
defmodule MyApp.Repo do
use Ecto.Repo, otp_app: :my_app, adapter: Ecto.Adapters.Postgres
def init(_, config) do
config =
Keyword.merge(config, [
username: MyApp.RepoConfig.get!(:username),
password: MyApp.RepoConfig.get!(:password),
database: MyApp.RepoConfig.get!(:database),
hostname: MyApp.RepoConfig.get!(:hostname)
])
{:ok, config}
end
end
Parsers
The parser is responsible for the conversion of environment variables into elixir types.
Custom parsers can be provided at the module or variable level:
defmodule MyApp.ConfigParser do
def parse(:string, value), do: {:ok, value}
def parse(:integer, value), do: #...
end
defmodule MyApp.ListParser do
def parse({:list, delimiter, subtype}, value) do
results =
value
|> String.split(delimiter)
|> Enum.map(&parse(subtype, &1))
case Enum.all?(results, fn {status, _} -> status == :ok end) do
true ->
{:ok, Enum.map(results, fn {_, value} -> value end)}
false ->
error =
%Cony.Parser.ParseError{
type: {:list, delimiter, subtype},
value: value,
message: "invalid list element"
}
{:error, error}
end
end
end
defmodule MyApp.Config do
import Cony
config parser: MyApp.ConfigParser do
add :some_text, :string
add :some_list, {:list, " ", :string}, parser: MyApp.ListParser
end
end