Decorate functions using macros in Elixir
After I decided to make public a telegram bot to monitor bus time in Dublin (@dublin_bus_bot). Before the release I became curious to see how many people will use it (spoiler: just an handful) and I thought that would be a good idea to track the use on google analytics.
Google analytics provide a measurement protocol that can be used to track things that are different from websites (mobile apps, IOT). At the moment no elixir client exists for this protocol (and it would not be anything more than an api wrapper). My plan is to make call to the Google Analytics TK endpoint with HTTPOison but I’d prefer to not have to call the tracking function for every single bot command.
One of the feature that I prefer of the elixir are macros, macros allow to generate code at compile time. I decided to define a macro that looking like a function definition would define a function with the same body and with an additional call to the track function. I decided this approach because seems more idiomatics than using the decorator syntax typical of other languages (
defmetered sample_function(arg1, arg2) do
I implemented this approach in meter to use in the telegram bot I wrote.
Elixir macros are a powerful tool to abstract away some functionality or to write DSLs. They require a bit of time to wrap head around, in particular with the context swith, but it totally worth the hassle if you can reduce the clutter in your code base.