Skip to content

Commit 14595bb

Browse files
authored
Add Config.read_config/1 (#13754)
1 parent 1889ee9 commit 14595bb

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

lib/elixir/lib/config.ex

+25
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,31 @@ defmodule Config do
194194
|> put_config()
195195
end
196196

197+
@doc """
198+
Reads the configuration for the given root key.
199+
200+
This function only reads the configuration from a previous
201+
`config/2` or `config/3` call. If `root_key` points to an
202+
application, it does not read its actual application environment.
203+
Its main use case is to make it easier to access and share
204+
configuration values across files.
205+
206+
If the `root_key` was not configured, it returns `nil`.
207+
208+
## Examples
209+
210+
# In config/config.exs
211+
config :my_app, foo: :bar
212+
213+
# In config/dev.exs
214+
config :another_app, foo: read_config(:my_app)[:foo] || raise "missing parent configuration"
215+
216+
"""
217+
@doc since: "1.18.0"
218+
def read_config(root_key) when is_atom(root_key) do
219+
get_config!()[root_key]
220+
end
221+
197222
@doc """
198223
Returns the environment this configuration file is executed on.
199224

lib/elixir/test/elixir/config_test.exs

+10
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,16 @@ defmodule ConfigTest do
6464
assert config() == [app: [{Repo, other: :value, key: :other}]]
6565
end
6666

67+
test "read_config/1" do
68+
assert read_config(:lager) == nil
69+
70+
config :lager, key: :value
71+
assert read_config(:lager) == [key: :value]
72+
73+
config :lager, other: :value
74+
assert read_config(:lager) == [key: :value, other: :value]
75+
end
76+
6777
@tag env: :dev
6878
test "config_env/0" do
6979
assert config_env() == :dev

0 commit comments

Comments
 (0)