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
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
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
Top comments (0)