NibbleConfig behaviour (nibble_config v0.1.0)

Copy Markdown View Source

NibbleConfig lets each module declare and load its own configuration, instead of scattering configuration across config/*.exs files.

Usage

Modules requiring configuration can implement the NibbleConfig behaviour, and declare and use their own configuration:

defmodule MyApp.MyExternalService do
  use NibbleConfig, otp_app: :my_app

  @impl NibbleConfig
  def load_config(_ctx) do
    [
      api_key: System.fetch_env!("API_KEY"),
      # `Config.config_env/0` and `Config.config_target/0` are automatically
      # imported so you can refine the configuration based on the env and target.
      timeout: if(config_env() == :prod, do: 5_000, else: 60_000)
    ]
  end

  def call_service(path) do
    # Read the configuration
    api_key = config(:api_key)
    timeout = config(:timeout)

    HttpClient.get(path, api_key, timeout)
  end
end

They then need to be declared in config/runtime.exs:

NibbleConfig.new()
|> NibbleConfig.load_for(:my_app, MyApp.MyExternalService)
|> NibbleConfig.load_for(:my_app, MyApp.SomeOtherService)
|> NibbleConfig.apply_config()

Summary

Callbacks

Returns this module's configuration, as a map or {key, value} pairs.

Functions

Declares the calling module as configuration for :otp_app.

Writes all loaded configuration to the application environment.

Loads module's configuration and stores it. The configuration is converted to a map before being stored.

Initialize a new, empty configuration loader.

Types

t()

@type t() :: %NibbleConfig{loaded_configs: loaded_configs()}

Callbacks

load_config(t)

@callback load_config(t()) :: Enumerable.t({key :: term(), value :: term()})

Returns this module's configuration, as a map or {key, value} pairs.

You can call config_env/0 and config_target/0 from this callback to refine the returned configuration based on the current environment.

Functions

__using__(opts)

(macro)

Declares the calling module as configuration for :otp_app.

Options

  • :otp_app (recommended) - the OTP app to get configuration from. Setting it defines a private config/1 function to fetch a single key of the module configuration from within itself, and a public loaded_configuration/0 returning the whole configuration map.

apply_config(nibble_config)

@spec apply_config(t()) :: :ok

Writes all loaded configuration to the application environment.

load_for(nibble_config, otp_app, module)

@spec load_for(t(), atom(), module()) :: t()

Loads module's configuration and stores it. The configuration is converted to a map before being stored.

module must implement the NibbleConfig behaviour.

new()

@spec new() :: t()

Initialize a new, empty configuration loader.