Parsing integer and boolean configurable variables in config.exs

Viewed 1054

I have configuration where I want to pass boolean and integer variables as env.

BOOLEAN_VARIABLE=false
INTEGER_VARIABLE=5000

I also have default configuration that I want to set if given env variable is not found. Here I am setting default value of boolean_variable to true and for integer_variable default value is 2000.

boolean_variable =
  case System.get_env("BOOLEAN_VARIABLE") do
    "false" -> false
    _ -> true
  end

integer_variable =
  case System.get_env("INTEGER_VARIABLE") do
    nil -> 2000
    value -> String.to_integer(value)
  end

I have ended up with dozens of calls in configuration while parsing these variables in config.exs. I was curious if there is better way to have this configuration.

1 Answers

You can save them as environment variables. You can have a .env or some other file where you store environment variables. Then in your config files, you can read them + you can set the default value.

Here is an example.

.env file
BOOLEAN_VARIABLE=false
INTEGER_VARIABLE=4000

System.get_env/2 function can have string based default value as the second argument.

In your elixir code you can do:

System.get_env("BOOLEAN_VARIABLE", "false") |> Config.parse_boolean
System.get_env("INTEGER_VARIABLE", "2000") |> Config.parse_integer # or String.to_integer

The benefit of this approach is:

  • Your configurable variables are read from environment
  • It's easy to change value directly in .env file and then just source it with source .env command.
  • For docker & docker-compose, you can directly set the variables.
  • Your elixir & phoenix app will stay modular.
  • You can avoid compile-time dependencies which can lead to very unpredictable behaviour in different environments.
Related