O'Reilly logo

Metaprogramming Elixir by Chris McCord

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required