Suppose I have a module defining a __using__
macro. It registers a module attribute attr
. I want every module that uses
it to automatically have a attrs/0
function that exposes the value of that attribute. However it does not work. Here’s my minimal example:
defmodule Test do
defmacro __using__(_options) do
quote do
Module.register_attribute(__MODULE__, :attr, accumulate: true, persist: true)
import unquote(__MODULE__), only: [attr: 1]
def attrs_not_working, do: @attr
end
end
defmacro attr(opts) do
quote bind_quoted: [attr: Macro.escape(opts)] do
@attr attr
end
end
end
defmodule UseTest do
use Test
attr(:hello_world)
def attrs_working, do: @attr
end
iex(36)> UseTest.attrs_working()
[:hello_world]
iex(37)> UseTest.attrs_not_working()
[]
Guess it has to do it @attr
meaning different things in different contexts. How would I do that?