DEV Community

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

Top comments (0)