Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mix.env/0 equivalent in production env?

Mix.env/0 works correctly in mix phoenix.server, but it fails to call in a production environment which is built with exrm. It makes sense because mix isn't included in the release build, but is there any equivalent of Mix.env/0?

(UndefinedFunctionError) undefined function Mix.env/0 (module Mix is not available)

I'm using Mix.env/0 like this in some code:

if Mix.env == :dev do
  # xxxxxx
else
  # xxxxxx
end
like image 888
hykw Avatar asked Mar 09 '16 10:03

hykw


2 Answers

You can simply define a config value for the environment:

config/prod.exs

config :my_app, :environment, :prod 

config/dev.exs

config :my_app, :environment, :dev 

You can then check that value using Application.get_env/3

if Application.get_env(:my_app, :environment) == :dev do 

However, I would recommend giving this more context. Let's say you want to conditionally apply an authentication plug in production, you could set the config to:

config :my_app, MyApp.Authentication,   active: true  if Application.get_env(:my_app, MyApp.Authentication) |> Keyword.get(:active) do   #add the plug 

This way, your conditions are feature based instead of environment based. You can turn them on and off regardless of environment.

like image 154
Gazler Avatar answered Nov 15 '22 09:11

Gazler


You can evoque Mix.env/0 as a module constant at compile time like this :

@env Mix.env
#...
if @env == :dev do
#...

Works like a charm with releases.

like image 45
canelle Avatar answered Nov 15 '22 09:11

canelle