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?
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.