Elixir phoenix 应该把全局控制器助手放在哪里

Elixir phoenix where should one put global controller helpers

我几乎所有的控制器都需要以下功能。 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

作为一种方法,您可以创建一个单独的模块并将其导入到 controller 函数的 web.ex 文件中。

像这样:

defmodule MyApp.Web do

# Some code...

  def controller do
    quote do

      # Some code ...

      import MyApp.CustomFunctions

      # Some code ...

    do
  end

# Some code...

end

通常这些会在一个插件中,添加到您的路由管道中。

Programming Phoenix中使用了这个例子:

  • 他们定义了一个具有 authenticate_user 功能的 Rumbl.Auth 模块
  • 他们通过 import Rumbl.Auth, only: [authenticate_user: 2]
  • 在路由器中安装了插件
  • 然后他们通过它传递请求 - pipe_through [:browser, :authenticate_user].