2016-05-06 81 views

回答

3

一個主要區別是,在__using__的代碼被稱爲和返回值,只要你叫use模塊中注入,而​​被調用,並執行後,所有的代碼直接在模塊內注入的返回值,只在模塊編譯之前。

一個簡單的程序來演示的區別:

defmodule When do 
    defmacro __using__(_) do 
    IO.inspect :using 
    __CALLER__.module |> Module.definitions_in |> IO.inspect 
    quote do end 
    end 

    defmacro __before_compile__(_) do 
    IO.inspect :before_compile 
    __CALLER__.module |> Module.definitions_in |> IO.inspect 
    quote do end 
    end 
end 

defmodule Main do 
    @before_compile When 
    use When 
    IO.puts "added `@before_compile` and `use`" 
    def add(x, y), do: x + y 
end 

輸出:

:using 
[] 
added `@before_compile` and `use` 
:before_compile 
[add: 2] 

ExUnit uses @before_compile定義返回所有的測試,以使其能夠爲ExUnit亞軍獲得的功能和運行所有測試。