Forem

Cover image for Cleaner LiveView Pipes
Mykolas Mankevicius
Mykolas Mankevicius

Posted on

Cleaner LiveView Pipes

I like my pipes and i like em clean!

@impl LiveView
def mount(%{"edition" => id}, _session, socket) do
  edition = Festival.get_edition_by_id!(id, actor: user(socket))

  socket
  |> assign_edition(edition, false)
  |> assign(patch_path: ~q"/:locale/admin/edition/#{edition}/edit")
  |> ok()
end
Enter fullscreen mode Exit fullscreen mode

Over the few years of using LiveView I've found this to be a nice improvement to the codebase.

defmodule SocketHelpers do
  @moduledoc """
  A collection of functions to help express pipes when processing live view responses.
  """

  alias Phoenix.LiveView.Socket

  @spec ok(Socket.t()) :: {:ok, Socket.t()}
  def ok(%Socket{} = socket), do: {:ok, socket}

  @spec noreply(Socket.t()) :: {:noreply, Socket.t()}
  def noreply(%Socket{} = socket), do: {:noreply, socket}

  @spec cont(Socket.t()) :: {:cont, Socket.t()}
  def cont(%Socket{} = socket), do: {:cont, socket}

  @spec halt(Socket.t()) :: {:halt, Socket.t()}
  def halt(%Socket{} = socket), do: {:halt, socket}

  @spec user(Socket.t()) :: map() | nil
  def user(%Socket{assigns: %{current_user: current_user}}), do: current_user

  @spec locale(Socket.t()) :: atom() | nil
  def locale(%Socket{assigns: %{locale: locale}}), do: locale

  @spec notify_parent(Socket.t(), any()) :: atom() | nil
  def notify_parent(%Socket{} = socket, message) do
    send(self(), message)
    socket
  end
end
Enter fullscreen mode Exit fullscreen mode

Take the SocketHelpers module from above and import it into your YourApp.live_view/0 helper:

def live_view do
  quote do
    use Phoenix.LiveView,
      layout: {OctafestWeb.Layouts, :app}

    importSocketHelpers

    alias Phoenix.LiveView

    unquote(html_helpers())
  end
end
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay