How to get a variable value from Environment files in Phoenix?

Sheharyar picture Sheharyar · Jun 23, 2015 · Viewed 11.1k times · Source

I'm deploying my first Phoenix Application, and I've specified the values of a variable in my Environment Files (dev.exs and prod.exs).

Now I'm trying to figure out how to access them in my Controllers.

# config/dev.exs
config :my_app, MyApp.Endpoint,
  http: [port: 4000],
  debug_errors: true,
  cache_static_lookup: false,
  my_var: "DEVELOPMENT VALUE"

# config/prod.exs
config :my_app, MyApp.Endpoint,
  http: [port: {:system, "PORT"}],
  url: [host: "example.com"],
  my_var: "PRODUCTION VALUE"

Answer

Sheharyar picture Sheharyar · Jun 23, 2015

Okay, found something. Elixir's Application.get_env/3 is the way to go:

get_env(app, key, default \\ nil)


But the problem with this is that the accessor command becomes very long for the current situation:

# Set value in config/some_env_file.exs
config :my_large_app_name, MyLargeAppName.Endpoint,
  http: [port: {:system, "PORT"}],
  url: [host: "example.com"],
  my_var: "MY ENV VARIABLE"

# Get it back
Application.get_env(:my_large_app_name, MyLargeAppName.Endpoint)[:my_var]

A better way would be to define them in a separate section:

config :app_vars,
  a_string: "Some String",
  some_list: [a: 1, b: 2, c: 3], 
  another_bool: true

and access them like this:

Application.get_env(:app_vars, :a_string)
# => "Some String"

Or you could fetch a list of all key-value pairs:

Application.get_all_env(:app_vars)           
# => [a_string: "Some String", some_list: [a: 1, b: 2, c: 3], another_bool: true]