Macro examples
Let's go through some more in-depth examples of using macros to accomplish some pretty cool things, things that are generally fairly difficult to accomplish in other languages.
Debugging and tracing
We'll start with a debugging/tracer module that will enable us to automatically trace the methods of our library.
Note
Of course, this is highly unnecessary since the Erlang VM itself is capable of adding this functionality for us without requiring anything from the developer.
As part of this example, we're going to dive into use
and __using__
. use
as it turns out, is a relatively simple function that invokes the __using__
macro of the module passed. This, in turn, injects the code of the __using__
macro.
For example, let's say we've defined a basic module, UsingTest
, as the following code:
defmodule UsingTest do defmacro __using__(_opts) do quote do IO.puts "I'm the __using__/1 of #{unquote(__MODULE__)}" end end end
If we then define another, very simple module, say...