Last active
January 31, 2022 23:47
-
-
Save kentaro/b9fc66cd1035f6b4a83d3d3aebffaeb2 to your computer and use it in GitHub Desktop.
Generate accessors for module attributes in Elixir
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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