Can "Application.get_env(..)" be used as a module attribute along with "runtime.exs"?

Just define the value in both config/{dev,test,prod}.exs and config/runtime.exs. Runtime will win if the key is the same. Consider:

If the key/value exists only in compile time config:

# config/dev.exs
config :my_app, :some_key, "Compile time!"

Application.get_env(:my_app, :some_key) => "Compile time!"

If you define it in both:

# config/dev.exs
config :my_app, :some_key, "Compile time!"

# config/runtime.exs
config :my_app, :some_key, "Runtime!"

and then in IEx:

Application.get_env(:my_app, :some_key) => "Runtime!"

That said, you cannot expect the module attributes to respect this, because they are generated at compile time and the runtime config does not yet exist.

I would switch to functions to save on disk and memory usage, anyways. See this from Sara Juric about how module attributes as constants have a potential gotcha: Blog Post: 10 Elixir gotchas - #16 by sasajuric

1 Like