在引用之外访问调用者模块属性

Accessing caller module attributes outside of quote do

我目前正在研究一些 elixir 宏有趣的东西。我有一个这样的模块:

defmodule MapUtils do

  @handlers "I don't want you"

  defmacro __using__(_) do
    quote do
      import MapUtils
      Module.register_attribute __MODULE__, :handlers, accumulate: true
      @handlers "I want you"
    end
  end

  defmacro test do
    IO.inspect @handlers
    quote  do
      IO.inspect(@handlers)
    end
  end
end

defmodule Test do
  use MapUtils

  def testowa do
    MapUtils.test
  end
end

Test.testowa

产生这样的结果:

"I don't want you"
["I want you"]

我想从引用块外部的调用者模块访问@handlers,以根据它的内容生成一些代码。就我的理解而言,首先检查正在执行,其次正在转换为 AST 并在不同的上下文中执行。

有没有办法在编译时从调用者模块访问@handlers?

如果我没有正确理解你的问题,你想要的是:

Module.register_attribute __MODULE__, :handlers, 
                          accumulate: true,
                          persist: true

变更前:

iex(6)> Test.module_info(:attributes)
[vsn: [95213125195364189087674570096731471099]]

变更后:

iex(13)> Test.module_info(:attributes)
[vsn: [95213125195364189087674570096731471099], handlers: ["I want you"]]

我偶然发现了 this

我意识到我可以这样用 __CALLER__ 调用它:

Module.get_attribute(__CALLER__.module, :handlers)

事实上,它 return 认为它的价值是 return。