Finalize Building Our Internationalization Library
Explore how to finalize an internationalization library in Elixir by inspecting generated ASTs using Macro.to_string and implementing compile-time optimizations for string interpolation. Understand how to generate efficient code that improves runtime performance and maintain clear, testable macros for translations.
Macro.to_string: Making sense of our generated code
Macro.to_string takes an AST and produces a string of the high-level Elixir source. It’s incredibly helpful when debugging our generated ASTs, especially for cases where many function heads are generated, such as in our Translator module.
The project
Let’s inspect the generated code that compile has produced so far by adding the following changes to our Translator module:
defmodule I18n do
use Translator
locale "en",
flash: [
hello: "Hello %{first} %{last}!",
bye: "Bye, %{name}!"
],
users: [
title: "Users",
]
locale "fr",
flash: [
hello: "Salut %{first} %{last}!",
bye: "Au revoir, %{name}!"
],
users: [
title: "Utilisateurs",
]
endOn line 6, we stored the result of the generated AST in a final_ast binding. Then on line 12, we printed the entire AST expanded as Elixir source using Macro.to_string.
To finish, we returned the final_ast ...