diff --git a/lib/elixir/lib/config.ex b/lib/elixir/lib/config.ex index 728a2b2cbd4..b31ebc54537 100644 --- a/lib/elixir/lib/config.ex +++ b/lib/elixir/lib/config.ex @@ -194,6 +194,31 @@ defmodule Config do |> put_config() end + @doc """ + Reads the configuration for the given root key. + + This function only reads the configuration from a previous + `config/2` or `config/3` call. If `root_key` points to an + application, it does not read its actual application environment. + Its main use case is to make it easier to access and share + configuration values across files. + + If the `root_key` was not configured, it returns `nil`. + + ## Examples + + # In config/config.exs + config :my_app, foo: :bar + + # In config/dev.exs + config :another_app, foo: read_config(:my_app)[:foo] || raise "missing parent configuration" + + """ + @doc since: "1.18.0" + def read_config(root_key) when is_atom(root_key) do + get_config!()[root_key] + end + @doc """ Returns the environment this configuration file is executed on. diff --git a/lib/elixir/test/elixir/config_test.exs b/lib/elixir/test/elixir/config_test.exs index cd6f30c5e5b..a19e54df7e3 100644 --- a/lib/elixir/test/elixir/config_test.exs +++ b/lib/elixir/test/elixir/config_test.exs @@ -64,6 +64,16 @@ defmodule ConfigTest do assert config() == [app: [{Repo, other: :value, key: :other}]] end + test "read_config/1" do + assert read_config(:lager) == nil + + config :lager, key: :value + assert read_config(:lager) == [key: :value] + + config :lager, other: :value + assert read_config(:lager) == [key: :value, other: :value] + end + @tag env: :dev test "config_env/0" do assert config_env() == :dev