Skip to content

Instantly share code, notes, and snippets.

@kentaro
Last active January 31, 2022 23:47
Show Gist options
  • Save kentaro/b9fc66cd1035f6b4a83d3d3aebffaeb2 to your computer and use it in GitHub Desktop.
Save kentaro/b9fc66cd1035f6b4a83d3d3aebffaeb2 to your computer and use it in GitHub Desktop.
Generate accessors for module attributes in Elixir
defmodule AttrAccessor do
defmacro __using__(opts) do
quote do
unquote(opts[:attrs])
|> Enum.each(fn attr ->
Module.register_attribute(unquote(opts[:target]), attr, persist: true)
end)
def method_missing(func, _args) do
if value = __MODULE__.__info__(:attributes)[func] do
Enum.at(value, 0)
else
raise("no such attribute")
end
end
def unquote(:"$handle_undefined_function")(func, args), do: method_missing(func, args)
end
end
end
defmodule Foo do
use AttrAccessor, target: __MODULE__, attrs: [:a, :b]
@a :value_a
@b :value_b
@c :value_c
end
Foo.a |> IO.inspect
Foo.b |> IO.inspect
Foo.c |> IO.inspect # raise an error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment