Declare:
defmodule MyApp.ViaMacros.Constants do
@moduledoc """
Apply with `use MyApp.ViaMacros.Constants, :app` or `import MyApp.ViaMacros.Constants, :app`.
Each constant is private to avoid ambiguity when importing multiple modules
that each have their own copies of these constants.
"""
def app do
quote do
# This method allows sharing module constants which can be used in guards.
@bar "barrific module constant"
defp app_version, do: "0.0.1"
defp app_author, do: "Felix Orr"
defp app_info, do: [app_version, app_author]
end
end
defmacro __using__(which) when is_atom(which) do
apply(__MODULE__, which, [])
end
end
Consume with use
:
defmodule MyApp.ViaMacros.ConsumeWithUse do
use MyApp.ViaMacros.Constants, :app
def foo() do
IO.puts app_version
IO.puts app_author
IO.puts inspect app_info
end
def foo(_bar) when is_bitstring(@bar) do
IO.puts "We just used bar in a guard: #{@bar}"
end
end
This method allows you to use the @some_constant
inside guards. I'm not even sure that the functions would be strictly necessary.