In a macro, can you access a module attribute outside quote
?. I know about Module.get_attributes/2
but I can only get it to work inside quote
. Outside quote
, it always returns nil
whenever I have tried.
Here’s an example:
defmodule MyMacros do
defmacro my_macro() do
module = __CALLER__.module
Module.get_attribute(module, :foo) |> IO.inspect(label: "outside quote")
quote do
Module.get_attribute(unquote(module), :foo) |> IO.inspect(label: "with unquoted module")
Module.get_attribute(__MODULE__, :foo) |> IO.inspect(label: "with __MODULE__")
end
end
end
defmodule UseMacros do
require MyMacros
@foo bar: 1
MyMacros.my_macro()
end
(On a side note: I formatted this with normal indentation, but the forum seems to render it incorrectly for some reason…)
Here’s the output this produces:
outside quote: nil
with unquoted module: [bar: 1]
with __MODULE__: [bar: 1]
This demonstrates that __CALLER__.module
is correctly getting the module, but when I try to use it outside quote
to get the module attribute, I get back nil
.
Any ideas why or if there’s any way to get this to work?