Macros Inject Code
Let’s pretend we’re the Elixir compiler. We read a module’s source top to bottom and generate a representation of the code we find. That representation is a nested Elixir tuple.
If we want to support macros, we need a way to tell the compiler that we’d like to manipulate a part of that tuple. We do that using defmacro, quote, and unquote.
In the same way that def defines a function, defmacro defines a macro. You’ll see what that looks like shortly. However, the real magic starts not when we define a macro, but when we use one.
When we pass parameters to a macro, Elixir doesn’t evaluate them. Instead, it passes them as tuples representing their code. We can examine this behavior using a simple macro definition that prints ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access