The using macro
Elixir also has a special macro, <module>.__using__/1
, which can be invoked by just calling the use/2
keyword. This is a special macro that doesn’t need us to explicitly call require
with the module first before calling the macro.
For example, let’s update BehaviorInjector
to define a __using__/1
macro:
behavior_injector.ex
defmodule BehaviorInjector do defmacro __using__(_options) do quote do def hello, do: IO.puts "Hello world!" end end end
Now, in order to call that macro, all we need to do is use the use/2
macro, as follows:
test_subject.ex
defmodule TestSubject do use BehaviorInjector end
In the preceding code, we only passed one argument to the use/2
macro because the second argument is optional. Now, we can see that the final result and the final behavior of TestSubject
remained unchanged: