Skip to content

Instantly share code, notes, and snippets.

@thiagomajesk
Created April 30, 2024 22:31
Show Gist options
  • Save thiagomajesk/23d547abe27bc8b6af2b5a0234335486 to your computer and use it in GitHub Desktop.
Save thiagomajesk/23d547abe27bc8b6af2b5a0234335486 to your computer and use it in GitHub Desktop.
Macro-based constants in Elixir
defmodule Constant do
@moduledoc """
Allows generating dynamic functions for the given list of values.
Accepts an enumerable with the of keys and values to be generated as functions.
"""
defmacro __using__(constants) do
[define_constants(constants), define_helpers()]
end
defp define_constants(constants) when is_list(constants) do
for {key, value} <- constants do
quote do
defp fetch_const(unquote(key)), do: unquote(value)
end
end
end
defp define_helpers() do
quote do
def const(name) when is_atom(name), do: fetch_const(name)
def const(name) when is_list(name), do: List.flatten(Enum.map(name, &fetch_const/1))
end
end
end
defmodule Colors do
use Constant, rgb: [:red, :green, :blue]
end
defmodule Greeter do
def greet(name) do
Enum.each(Colors.const(:rgb), fn color ->
IO.puts(IO.ANSI.format([color, "Hello #{name}"]))
end)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment