Elixir phoenix where to put global controller assistants

I need the following functions for almost all controllers. Does Elixir have an ApplicationController module?

Where should we put them?

def redirect_if_unauthorized(conn = %Plug.Conn{assigns: %{authorized: false}}, opts) do conn |> put_flash(:error, "You can't access that page!") |> redirect(to: "/") |> halt end def redirect_if_unauthorized(conn = %Plug.Conn{assigns: %{authorized: true}}, opts), do: conn 
+5
source share
2 answers

As one of the methods, you can create a separate module and import it into the web.ex file in the controller .

Like this:

 defmodule MyApp.Web do # Some code... def controller do quote do # Some code ... import MyApp.CustomFunctions # Some code ... do end # Some code... end 
+7
source

Typically, this will be inside a Plug added to your routing pipeline.

This example is used in Phoenix programming:

  • they define a Rumbl.Auth module with authenticate_user function
  • they enable the plug-in in the router through import Rumbl.Auth, only: [authenticate_user: 2]
  • Then they process requests through it - pipe_through [:browser, :authenticate_user] .
+3
source

Source: https://habr.com/ru/post/1239190/


All Articles