Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Approach for constants shared between modules in Elixir
defmodule Constants do
@moduledoc """
An alternative to use @constant_name value approach to defined reusable
constants in elixir.
This module offers an approach to define these in a
module that can be shared with other modules. They are implemented with
macros so they can be used in guards and matches
## Examples:
Create a module to define your shared constants
defmodule MyConstants do
use Constants
define something, 10
define another, 20
end
Use the constants
defmodule MyModule do
require MyConstants
alias MyConstants, as: Const
def myfunc(item) when item == Const.something, do: Const.something + 5
def myfunc(item) when item == Const.another, do: Const.another
end
"""
defmacro __using__(_opts) do
quote do
import Constants
end
end
@doc "Define a constant"
defmacro constant(name, value) do
quote do
defmacro unquote(name), do: unquote(value)
end
end
@doc "Define a constant. An alias for constant"
defmacro define(name, value) do
quote do
constant unquote(name), unquote(value)
end
end
end
@houmanka

This comment has been minimized.

Copy link

@houmanka houmanka commented Jan 22, 2018

Perfect. Thank you :)

@DerKastellan

This comment has been minimized.

Copy link

@DerKastellan DerKastellan commented Mar 9, 2018

This generally works fine:
defmacro constant(name, value) do
quote do
defmacro unquote(name), do: unquote(value)
end
end

But if you use it in some other context, like for example this:

for {name, value} <- [ some_list_of_name_value_pairs ] do
constant(name, value)
end

I get a problem because it doesn't work with variables bound from the environment, at least not in elixir 1.3.4

I have a modified version that works for me:

defmacro constant(key, entry) do
quote bind_quoted: [key: key, entry: entry] do
def unquote(key)() do
unquote(entry)
end
end
end

This ties values from the caller environment into the definition... IIRC. Anyway - for my purposes that version worked better.

@guzishiwo

This comment has been minimized.

Copy link

@guzishiwo guzishiwo commented Apr 7, 2019

66666666

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.