Pra*_*oya 8 elixir phoenix-framework
我几乎在所有控制器中都需要以下功能.在Elixir中是否有类似ApplicationController的模块?
我们应该把它们放在哪里?
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
Run Code Online (Sandbox Code Playgroud)
作为一种方法,您可以创建一个单独的模块并将其导入web.ex到controller函数中的文件中.
像这样:
defmodule MyApp.Web do
# Some code...
def controller do
quote do
# Some code ...
import MyApp.CustomFunctions
# Some code ...
do
end
# Some code...
end
Run Code Online (Sandbox Code Playgroud)
通常,它们将在插件内,并添加到路由管道中。
该示例在Phoenix编程中使用:
Rumbl.Auth带有authenticate_user功能的模块import Rumbl.Auth, only: [authenticate_user: 2]pipe_through [:browser, :authenticate_user]。