Code Injection and the Caller’s Context

Macros don’t just generate code for the caller, they inject it. We call the place where code is injected a context. A context is the scope of the caller’s bindings, imports, and aliases. To the caller of a macro, the context is precious. It holds your view of the world, and by virtue of immutability, you don’t expect your variables, imports, and aliases to change out from underneath you.

Elixir macros strike an excellent balance for safeguarding your context while allowing explicit access where neccesary. Let’s see how to inject code safely and the available tools to reach into the caller’s context when necessary.

Injecting Code

Because macros are all about injecting code, you have to understand the two ...

Get Metaprogramming Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.