Get current environment name

前端 未结 4 1606
野性不改
野性不改 2020-12-28 15:49

In Phoenix Framework, how can I get the current environment\'s name ?

I\'ve already tried reading env variables with System.get_env(\"MIX_ENV\")

相关标签:
4条回答
  • 2020-12-28 16:18

    Mix.env() doesn't work in production or other environments where you use compiled releases (built using Exrm / Distillery) or when Mix just isn't available.


    The solution is to specify it in your config/config.exs file:

    config :your_app, env: Mix.env()
    

    You can then get the environment atom in your application like this:

    Application.get_env(:your_app, :env)
    #=> :prod
    
    0 讨论(0)
  • 2020-12-28 16:20

    Now in each environment config file (e.g. prod.exs) generated by default, you'll see the environment atom being set at the last line:

    config :your_app, :environment, :prod

    You can then use Application.get_env(:your_app, :environment) to get it.

    You can do the same in any custom environment config you create.

    0 讨论(0)
  • 2020-12-28 16:27

    You can use Mix.env/0:

    iex(1)> Mix.env
    :dev
    
    0 讨论(0)
  • 2020-12-28 16:35

    An alternative to putting the Mix.env/0 into your applications configuration is to use a module attribute. This also works in production because module attributes are evaluate at compile time.

    defmodule MyModule do
      @env Mix.env()
    
      def env, do: @env
    end
    

    If you only need the environment in a specific place - for example when starting up the application supervisor - this tends to be the easier solution.

    0 讨论(0)
提交回复
热议问题