Using Module Attributes for Code Generation

Before we can implement the test macro, we need to address a missing piece to our implementation. A user can define multiple test cases, but we have no way of tracking each test-case definition for inclusion within MathTest.run/0. Fortunately, Elixir solves this use case via module attributes.

Module attributes allow data to be stored in the module at compile time. They are often used in places where constants would be applied in other languages, but Elixir provides other tricks for us to exploit during compilation. By taking advantage of the accumulate: true option when registering an attribute, we can keep an appended list of registrations during the compile phase. After the module is compiled, the ...

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.