Question

I defined a environment variable related to the guide-started, my mix.exs is

defmodule Basic.Mixfile do
  use Mix.Project

  def project do
    [app: :basic,
     version: "0.0.1",
     elixir: "~> 0.13.0-dev",
     deps: deps,
     env: [
      dev: [foo: "bar"] ] ]
  end

  # Configuration for the OTP application
  #
  # Type `mix help compile.app` for more information
  def application do
    [ applications: [],
      mod: { Basic, [] } ]
  end

  # List all dependencies in the format:
  #
  # { :foobar, git: "https://github.com/elixir-lang/foobar.git", tag: "0.1" }
  #
  # Type `mix help deps` for more examples and options
  defp deps do
    []
  end
end

and then I start the project with iex -S mix or MIX_ENV=dev iex -S mix, I want to get the environment variable with :application.get_env(:basic, :foo) , it turned to :undefined; and use :application.get_all_env(:basic), it returned [included_applications: []], there is not the env variable. And my question is how should I get the environment value?

Was it helpful?

Solution

The :env must not be specified in project but inside the application one.

def application do
  [ applications: [],
    mod: { Basic, [] },
    env: [foo: :bar] ]
end

Then you can access it as:

Application.get_env(:basic, :foo)

In this case, there is no support for specifying the environment for a particular MIX_ENV (like dev or prod). This is exactly why :env inside project is deprecated. Having two keys being named :env with different behaviour is recipe for confusion. :)

OTHER TIPS

I think Mix.project[:foo] returns the defined value ("bar") when MIX_ENV is dev. However, as the following warning is being displayed at v0.13.1, it may not be the recommended way.

"The :env key in Basic.Mixfile project configuration is deprecated" 

If it's used for configuration setting, https://github.com/phoenixframework/ex_conf has environment-based configuration features too.

Use env = :application.get_env(:example, Mix.env). That will return the keyword list you've defined under the :dev key in your mix.exs file. You can then use Keyword.get(env, :foo) to extract the individual keys.

It may be overkill for your needs, but Avdi Grimm recently ported dotenv to Elixir.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top