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
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
Typically these would be inside a Plug, added to your routing pipeline.
This example is used in Programming Phoenix:
Rumbl.Auth
module with an authenticate_user
functionimport Rumbl.Auth, only: [authenticate_user: 2]
pipe_through [:browser, :authenticate_user]
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With