Skip to content

Instantly share code, notes, and snippets.

@KazuCocoa
Last active April 19, 2016 22: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 KazuCocoa/de6eb692040443a31a80d25ad3e67b16 to your computer and use it in GitHub Desktop.
Save KazuCocoa/de6eb692040443a31a80d25ad3e67b16 to your computer and use it in GitHub Desktop.
defmodule Functions do
# switch using `def` or `defp` in compile time
defmacro defpt(func, body \\ nil) do
case test_env? do
true -> quote do: def(unquote(func), unquote(body))
false -> quote do: defp(unquote(func), unquote(body))
end
end
defp test_env? do
case System.get_env "MIX_ENV" do
"test" -> true
_ -> false
end
end
end
defmodule Defpt do
defmacro __using__(_) do
quote do
import Functions
end
end
end
defmodule Alexa do
use Defpt
# use defpt which defines as macro
defpt hello do
"hi"
end
end
# Failed call Alexa.hello if MIX_ENV is not "test"
# Anyone can't find Alexa.hello is used or unused by warning in compile time
# or should cover coverage.
# iex> Me.inu
# ** (UndefinedFunctionError) undefined function Alexa.hello/0
# Alexa.hello()
# neko.exs:37: Me.inu/0
defmodule Me do
def inu do
IO.puts Alexa.hello
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment