raarts
raarts

Reputation: 2961

Is it possible in Elixir to have code conditionally present depending on Mix environment?

Basically like #ifdef/#else/#endif in C/C++ I want some code top be present during mix test and removed in production, so I don't need to test for Mix.env == :test in a piece of code that is very often called.

I know it's considered bad practice, but is it possible and how?

Upvotes: 1

Views: 1096

Answers (2)

bryan hunt
bryan hunt

Reputation: 35

There's a variant that's worth mentioning - loading env specific code after build - here's one I use to grab an env specific seeds file :

# Capture the mix environment at build time
defmacro mix_build_env() do
  Atom.to_string( Mix.env )
end

def seeds_path(repo) do
  mix_env = mix_build_env()
  # IO.puts(:stderr, "env:  #{inspect x} " )
  priv_path_for(repo, mix_env  <>  "_seeds.exs")
end

Upvotes: 0

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

While building a release, Mix is available. In the release itself, it is not. If you are positive you want the code to be stripped out from the release version, use a macro:

defmodule StrippedInRelease do
  defmacro fun(do: block) do
    if Mix.env == :test do
      block # AST as by quote do: unquote(block)
    end
  end
end

and use it like:

require StrippedInRelease
StrippedInRelease.fun do
  def yo, do: IO.puts "¡yo!"
end

It is to be expanded during a compilation time and, hence, everything passed as a block will be defined in the :test environment and stripped out in other environments.

Upvotes: 4

Related Questions