How to use if or other condition for "dev" or "prod"

Hi!
I want to do something like this.
if MIX_ENV == “dev” do
do if in local dev environment
else
do if in production environment
end

Is this possible?

In my experience, this a bad idea and there are many times that this can be avoided (but not always).

First of all, Mix is a tool which is not available in a release, so it can be dangerous if you use in dev.

I don’t know what you are trying to do, but for example, if you don’t want to send emails in dev, it should have its own configuration. Maybe this configuration relays on an environment variable in production, but it should not have a generic name, it would be better something like MAIL_CONFIG.

Maybe the following links help:


https://hexdocs.pm/mix/Mix.Config.html

1 Like

i tried this in config.exs and it works

if "#{Mix.env}" === "dev" do
  IO.puts "I am in dev environment"
end

In the config, this construct is safe to use, but I’m wondering why you don’t use environment specific config files?

Also instead of stringifying you should compare atoms directly: Mix.env() == :dev

You can add config :myapp, :environment, :dev to dev.exs and config :myapp, :environment, :prod to prod.exs and then in your function:

if (Application.get_env(:myapp, :environment) == :prod) do
  # prod branch
else
  # dev/test branch
end

If you want to do it at runtime

if unquote(Mix.env == :dev) do # would compile to true or false
  # ...
else
  # ...
end

However I prefer to compile different functions / bodies depending on the mix env / runtime version, rather than using if branching inside of them.

defmodule SomeModule do
  if Mix.env == :test do
    def func(), do: :ok  
  else
    def func(), do: # actually do soemthing
  end
end

but I use it very rarely (mostly in routers / plug pipelines), something like a protocol is usually a cleaner approach.

Why not

if Mix.env == :dev do
  IO.puts "I am in dev environment"
end

?

Since config.exs is only evaluated during compilation, it’s safe to call Mix.env without unquoting there.

From what I understand, he wants his code to behave differently when deployed.

As @alexcastano mentioned, Mix is not available in a release. It will work while you run in dev but will not work in the production environment.

That’s why you should use unquote(Mix.env == :dev) during runtime … And config.exs is not being evaluated in a release, so it doesn’t matter.