-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating
Elixir Cookbook
By :
Mix tasks run in a specific environment. The predefined environments are production, development, and test (prod, dev, and test). The default environment is dev. In this recipe, we will configure an application with different values for each environment. Invoking the same function will result in a different output based on the configuration.
To manage an application configuration, we follow these steps:
> mix new config_example
config/config.exs.use Mix.Config
config :config_example,
message_one: "This is a shared message!"
import_config "#{Mix.env}.exs"config directory with the following code:config/dev.exs, add the following:use Mix.Config config :config_example, message_two: "I'm a development environment message!"
config/prod.exs, add this code:use Mix.Config config :config_example, message_two: "I'm a production environment message!"
config/test.exs, add the following:use Mix.Config config :config_example, message_two: "I'm a test environment message!"
lib/config_example.ex to hold the values of message_one and message_two, as follows:@message_one Application.get_env(:config_example, :message_one) @message_two Application.get_env(:config_example, :message_two)
show_messages function in lib/config_example.ex, like this:def show_messages do
IO.puts "Message one is: #{@message_one}"
IO.puts "Message two is: #{@message_two}"
endshow_messages function:> MIX_ENV=dev iex –S mix iex(1)> ConfigExample.show_messages Message one is: This is a shared message! Message two is: I'm a development environment message! :ok iex(2)>
> MIX_ENV=prod iex –S mix iex(1)> ConfigExample.show_messages Message one is: This is a shared message! Message two is: I'm a production environment message! :ok iex(2)>
> MIX_ENV=test iex –S mix iex(1)> ConfigExample.show_messages Message one is: This is a shared message! Message two is: I'm a test environment message! :ok iex(2)>
When we include the last line in config.exs (import_config "#{Mix.env}.exs"), the Mix configuration is loaded from the files, in this case with the Mix environment as its name and .exs as its extension.
The configuration from the imported files will override any existing configuration (with the same key) in the config.exs file. In fact, Configuration values are merged recursively. See the example at https://github.com/alco/mix-config-example.
To access configuration values, we use Application.get_env(:app, :key).
Change the font size
Change margin width
Change background colour