I wanted to add how I've started doing constants, which is similar to @Onorio Catenacci's answer, but uses quoting:
defmodule IbGib.Constants do
@doc """
Use this with `use IbGib.Constants, :ib_gib`
"""
def ib_gib do
quote do
defp delim, do: "^"
defp min_id_length, do: 1
# etc...
end
end
@doc """
Use this with `use IbGib.Constants, :error_msgs`
"""
def error_msgs do
quote do
defp emsg_invalid_relations do
"Something about the rel8ns is invalid. :/"
end
# etc...
end
end
@doc """
When used, dispatch to the appropriate controller/view/etc.
"""
defmacro __using__(which) when is_atom(which) do
apply(__MODULE__, which, [])
end
end
And then you use it like this at the top of the module where you want to consume them:
use IbGib.Constants, :ib_gib # < specifies only the ib_gib constants
use IbGib.Constants, :error_msgs
# ... then in some function
Logger.error emsg_invalid_relations
I got this with how Phoenix does import/use clauses with MyApp.Web. I'm nowhere near an Elixir expert, but with this method you can import just those constants that you want and you don't need to prefix them with any namespacing/scoping. This way, you can pick and choose the individual groups of constants easily.
With straight functions, (I think) you would have to break them up into multiple modules and then import the module.
I don't know the optimization ramifications of this vs direct module functions, but I thought it was pretty neat - especially for practice between the various ways to "import" things in Elixir (import
, use
, alias
, require
is very confusing as a beginner coming from other languages where this is a single using
or import
statement).
EDIT: I've changed the constant def
declarations to defp
. This is because when multiple modules import
the constants file, there is an ambiguity conflict. Changing them to privately scoped functions avoids this conflict. So each module has its own "private copy" of the same constant.