Chen Yu
Chen Yu

Reputation: 4077

In iex, why `config_env()` can't be called?

My code is as follows, I just want to know current's env is test or dev. What's the problem here?

iex(8)> import Config
Config
iex(9)> config_env() 
** (RuntimeError) could not set configuration via Config. This usually means you are trying to execute a configuration file directly, instead of reading it with Config.Reader
    (elixir 1.14.1) lib/config.ex:111: Config.raise_improper_use!/0
    (elixir 1.14.1) lib/config.ex:218: Config.__env__!/0

Upvotes: 2

Views: 830

Answers (1)

Adam Millerchip
Adam Millerchip

Reputation: 23101

Config is usually compile-time or application start-time, there is no "current env" once you are running in iex after your application has started.

From the docs for config_env/0 (emphasis mine):

Returns the environment this configuration file is executed on.

This function expects to be called from within a configuration file. Normally you would use Config to create application environment variables, then use Application.get_env/3 to fetch those variables at runtime. It's an anti-pattern to write runtime logic that relies on knowing what the configuration environment was - instead you should get the specific data you need from application environment.

Upvotes: 3

Related Questions