Skip to content

Add Config.read_config/1 #13754

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions lib/elixir/lib/config.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
10 changes: 10 additions & 0 deletions lib/elixir/test/elixir/config_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading