What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
System.get_env/3
gets from the system environment, while Application.get_env/3
gets from the applications environment.
The first is defined by the means of your operating system, while the later is mostly configured during build using the file(s) in config
and local to your application.
The application environment is described in the docs: https://hexdocs.pm/elixir/Application.html#module-application-environment
The system-environment is not, since it is not any part of elixir or the BEAM. It’s just there…
My rule of thumb is to only use System.get_env
during application initialization, eg in your Application.start
, Repo.init
, Endpoint.init
callbacks.
Once the application is initialized, the environment should always be queried by Application.get_env
, since System.get_env
can only return strings.
I like the dev
/ test
environment to be statically defined in the config.exs files, only reading from the system environment for prod
builds.
Replies above explain the difference between Application.get_env
and System.get_env
.
As for best practices, have a look at this: https://elixirschool.com/blog/configuration-demystified/
The documentation for these should make it much clearer whether these values are read just once at build time, or every time at runtime. (I’m having to do some extra googling to figure this out, when I could have had the answer already.)
The documentation can’t do that, because that depends on where those functions are called, not which function is called.
Ah… good point. a value retrieval is a value retrieval, whether it happens once (at build) or many times (at runtime) depends on the caller. Of course.