Extending modules

After understanding how macros work, we will now apply the insights we just got to see how we can create macros that add functionality to the caller module. Our objective here is to create a macro, ElixirDrip.Chronometer.defchrono/2, equivalent to the existing def/2 macro but with the additional feature that logs how long the function call took.

Let's start by looking at the end result. We want to be able to define functions such as defchrono fun_name(arg1, arg2), do: ... and when we call the fun_name/2 function, it will tell us Took 123 µs to run SomeModule.fun_name/2. The following MeasuredModule will be our research subject:

$ cat examples/measured_module.exsdefmodule MeasuredModule do  import ElixirDrip.Chronometer defchrono_vn ...

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