Programming Phoenix LiveView B3.0 P215: Repeated code snippets

repeated code.

assign_chart_svg is repeated verbatim a few lines down.

render_bar_chart is repeated in an expanded form a few lines down.

Presumably a leftover from a previous edit.

Edit: The second, expanded, version of render_bar_chart is the one to use, as it adds the titles and axis labels. HOWEVER, it will not work without the addition of “Contex.” before the Plot calls.

i.e.

Plot.new

doesn’t work.

Contex.Plot.new

does

def assign_chart_svg(%{assigns: %{chart: chart}} = socket) do
socket
|> assign(:chart_svg, render_bar_chart(chart))
end

defp render_bar_chart(chart) do
Contex.Plot.new(500, 400, chart)
end

There are no surprises here. We merely tack another reducer onto the chain. This one renders the bar chart, and assigns the result to the socket. We’ll customize our plot with some titles and labels for the x- and y-axis:

lib/pento_web/live/survey_results_live.ex

def assign_chart_svg(%{assigns: %{chart: chart}} = socket) do
socket
|> assign(:chart_svg, render_bar_chart(chart))
end

defp render_bar_chart(chart) do
Plot.new(500, 400, chart)
|> Plot.titles(title(), subtitle())
|> Plot.axis_labels(x_axis(), y_axis())
end

Thanks for pointing this out @asibbald! You’re correct that the Contex prefix was missing from the second render_bar_chart/1 function, I’ll fix that :slight_smile:

The repeated code isn’t so much repeated as its being added on to. I’m going to cut the repeated appearance of assign_chart_svg from the code example from the two appearances of render_bar_chart/1 are there because the second example is meant to walk you through the new content to add to the function. I’ll make that more clear in the next revision!