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