Skip to content

Instantly share code, notes, and snippets.

@andreapavoni
Last active May 24, 2017 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreapavoni/4adef15c3af4c869f7733f2dab2017da to your computer and use it in GitHub Desktop.
Save andreapavoni/4adef15c3af4c869f7733f2dab2017da to your computer and use it in GitHub Desktop.
Running a block code only with a specific Mix.env

Ever found yourself writing code like this?

case Mix.env() do
  :prod -> do_something1()
  :dev  -> do_something2()
  :test -> do_something3()
end

I wrote a macro to solve this annoying use case:

MyApp.MyModule do
  import RunForEnvs, only: [run_for_envs: 2]
  
  run_for_envs [:dev] do
    do_something2()
  end
end
defmodule RunForEnvs do
@doc """
A macro that runs the `block` if the current `Mix.env` is inside passed `envs`.
"""
defmacro run_for_envs(envs, block) do
quote do
if (Mix.env in unquote(envs)), do: unquote(block)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment