2016-09-15 27 views
1

我目前正在研究一些靈丹妙藥有趣的東西。我有一個這樣的模塊:訪問報價外的來電模塊屬性

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?

回答

1

我在迷迷糊糊this

我意識到我可以__CALLER__這樣稱呼它:

Module.get_attribute(__CALLER__.module, :handlers) 

而事實上它返回的值是假設返回。

1

如果我正確理解你的問題,你想這樣:

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"]]