...

/

How to Refactor Chart Code with Macros

How to Refactor Chart Code with Macros

Let's learn how to make your LiveView re-usable with Macros.

Our SurveyResultsLive component has a fair bit of charting support, in addition to the typical LiveView functions that set and change the socket. This kind of charting logic and configuration should live elsewhere so other components can take advantage of it as well.

Let’s refactor the chart code by extracting common code into a __using__ macro. In return for these efforts, your LiveView logic will be clean and re-usable.

Here’s how it works.

How to refactor with using

At the top of every LiveView we’ve written so far, we can see the call to use PentoWeb, :live_view. The use directive calls the __using__ macro on the PentoWeb module.

That code in turn returns code that is injected into our LiveView modules. Let’s take a look at it in pento/lib/pento_web.ex:

Press + to interact
def live_view do
quote do
use Phoenix.LiveView,
layout: {PentoWeb.LayoutView, "live.html"}
unquote(view_helpers())
end
end
...
defmacro __using__(which) when is_atom(which) do
apply(__MODULE__, which, [])
end

At the bottom of the file, you’ll see a __using__ macro on line 10. Think of macros as Elixir code that writes and injects code. When a LiveView module calls use ...