-
-
Notifications
You must be signed in to change notification settings - Fork 42
/
config.ex
69 lines (55 loc) · 1.65 KB
/
config.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
defmodule Assent.Config do
@moduledoc """
Methods to handle configurations.
"""
defmodule MissingKeyError do
@type t :: %__MODULE__{}
defexception [:key]
def message(exception) do
"Key #{inspect(exception.key)} not found in config"
end
end
@type t :: Keyword.t()
@doc """
Fetches the key value from the configuration.
"""
@spec fetch(t(), atom()) :: {:ok, any()} | {:error, MissingKeyError.t()}
def fetch(config, key) do
case Keyword.fetch(config, key) do
{:ok, value} -> {:ok, value}
:error -> {:error, MissingKeyError.exception(key: key)}
end
end
defdelegate get(config, key, default), to: Keyword
defdelegate put(config, key, value), to: Keyword
defdelegate merge(config_a, config_b), to: Keyword
@doc """
Fetches the JSON library in config.
If not found in provided config, this will attempt to load the JSON library
from global application environment for `:assent`. Defaults to `Jason`.
"""
@spec json_library(t()) :: module()
def json_library(config) do
case get(config, :json_library, nil) do
nil ->
Application.get_env(:assent, :json_library, Jason)
json_library ->
json_library
end
end
# TODO: Remove in next major version
def __base_url__(config) do
case fetch(config, :base_url) do
{:ok, base_url} ->
{:ok, base_url}
{:error, error} ->
case fetch(config, :site) do
{:ok, base_url} ->
IO.warn("The `:site` configuration key is deprecated, use `:base_url` instead")
{:ok, base_url}
{:error, _site_error} ->
{:error, error}
end
end
end
end