Code injection using macros
We learned that we can use Code.eval_quoted/3
to dynamically add behavior to a module, but Elixir provides a cleaner and more consistent way of doing this, using macro
.
Code.eval_quoted/3
allows us to inject code using a set of variable bindings and an environment. macro
, on the other hand, allows us to define a set of quoted literals at the time of their compilation and evaluate the expressions, by simply invoking it like a function inside another module. A macro can be defined by using defmacro/2
, which itself is a macro.
To understand the preceding distinction better, let us use macro
to implement the same BehaviorInjector
module and inject behavior in the TestSubject
module:
behavior_injector.ex
defmodule BehaviorInjector do defmacro define_hello do quote do def hello, do: IO.puts "Hello world!" end end end
In the preceding...