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

Generate Less Code by Walking the AST

Our Html module is clear and concise, but we did have to generate well over a hundred macros to make it work. Wouldn’t it be nice to generate less code but still maintain our expressive DSL where all tags can be used as macro calls? Let’s make it happen.

You might think that maintaining our DSL without generating all HTML macros sounds impossible, but step back and remember that Elixir gives you full AST access. For example, open up an iex prompt and quote a few arbitrary HTML DSL expressions, and let’s look at the results. Do not load your Html module since we are just quoting raw expressions outside the context of our library for this example.

 
iex>​ ast = ​quote​ ​do​​​
 
...>​ div ​do​​​
 
...>​ h1 ​ ...

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