Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir phoenix where should one put global controller helpers

I need the following functions in almost all controllers. Is there an ApplicationController like module in Elixir?

Where should we put these?

  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
like image 941
Pratik Khadloya Avatar asked Dec 25 '15 07:12

Pratik Khadloya


2 Answers

As one way to go, you could create a separate module and import it in the web.ex file in the controller function.

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
like image 137
NoDisplayName Avatar answered Nov 20 '22 00:11

NoDisplayName


Typically these would be inside a Plug, added to your routing pipeline.

This example is used in Programming Phoenix:

  • they define a Rumbl.Auth module with an authenticate_user function
  • they include the plug in their router via import Rumbl.Auth, only: [authenticate_user: 2]
  • they then pipe requests through it - pipe_through [:browser, :authenticate_user].
like image 24
sevenseacat Avatar answered Nov 20 '22 01:11

sevenseacat