Packages
A dead-simple config provider module that plugs into Elixir 1.9 release config and parses TOML config files on startup. It is meant as a replacement for Toml.Provider, which only works with Distillery.
Current section
Files
Jump to
Current section
Files
lib/toml_config_provider.ex
defmodule TomlConfigProvider do
@moduledoc """
A dead-simple config provider module that plugs into Elixir 1.9 release
config. It is meant as a replacement for Toml.Provider, which only works
with Distillery.
"""
@behaviour Config.Provider
def init(path) when is_binary(path), do: path
@doc """
Callback required by the `Config.Provider` behavior.
Reads the TOML config file `path` and merges it with `config`.
"""
def load(config, path) do
decoded = read!(path)
Config.Reader.merge(config, decoded)
end
@doc """
Reads a TOML file and transforms it to a format that can be
easily merged with existing configuration using `Config.Reader.merge/2`
or used independently.
"""
def read!(path) do
File.read!(path) |> parse!()
end
@doc """
Parses a binary formatted as TOML and transforms it to a format
that can be used for configuration. This function is called
under the hood by `load/2` and `read!/1`.
"""
def parse!(binary) when is_binary(binary) do
Toml.decode!(binary, keys: :atoms) |> transform()
end
@doc """
BEAM configuration expects nested keyword lists, therefore we recursively convert
each nested map into keyword lists.
"""
def transform(val), do: transform(val, 0)
# Only transform maps in the first three levels of configuration -- some people may
# need maps in their configuration deeper in the tree.
defp transform(val, 3), do: val
defp transform(enum, level) when is_map(enum) or is_list(enum) do
Enum.map(enum, fn x -> transform(x, level + 1) end)
end
defp transform({k, v}, level) do
{k, transform(v, level)}
end
defp transform(other, _level), do: other
end