【发布时间】:2015-12-28 00:06:48
【问题描述】:
我正在使用 Phoenix 框架并尝试创建用于身份验证的插件,但遇到错误。下面是这个示例代码。
defmodule ChhutiServer.GoogleAuthController do
use ChhutiServer.Web, :controller
use ChhutiServer.Plugs.GoogleAuth
end
# inside lib/plugs
defmodule ChhutiServer.Plugs.GoogleAuth do
import Plug.Conn
defmodule ChhutiServer.Behaviour.GoogleAuth do
@callback callback(Plug.Conn.t, map) :: any
end
defmacro __using__(_) do
quote do
plug ChhutiServer.Plugs.GoogleAuth
end
end
end
上面的代码返回下面的错误。
== Compilation error on file web/controllers/google_auth_controller.ex ==
** (UndefinedFunctionError) undefined function: ChhutiServer.Plugs.GoogleAuth.ChhutiServer.Plugs.GoogleAuth.init/1 (module ChhutiServer.Plugs.GoogleAuth.ChhutiServer.Plugs.GoogleAuth is not available)
ChhutiServer.Plugs.GoogleAuth.ChhutiServer.Plugs.GoogleAuth.init([])
(plug) lib/plug/builder.ex:198: Plug.Builder.init_module_plug/3
(plug) lib/plug/builder.ex:186: anonymous fn/4 in Plug.Builder.compile/3
(elixir) lib/enum.ex:1387: Enum."-reduce/3-lists^foldl/2-0-"/3
(plug) lib/plug/builder.ex:186: Plug.Builder.compile/3
(phoenix) expanding macro: Phoenix.Controller.Pipeline.__before_compile__/1
web/controllers/google_auth_controller.ex:1: ChhutiServer.GoogleAuthController (module)
(elixir) lib/kernel/parallel_compiler.ex:100: anonymous fn/4 in Kernel.ParallelCompiler.spawn_compilers/8
我了解错误是由于 Elixir 寻找 ChhutiServe.Plugs.GoogleAuth.ChhuttiServer.Plugs.GoogleAuth 而不是 ChhuttiServe.Plugs.GoogleAuth。而且我还可以通过在模块前面加上 Elixir 命名空间来解决这个问题。即通过使用下面的代码。
defmodule ChhutiServer.Plugs.GoogleAuth do
import Plug.Conn
defmodule ChhutiServer.Behaviour.GoogleAuth do
@callback callback(Plug.Conn.t, map) :: any
end
defmacro __using__(_) do
quote do
plug Elixir.ChhutiServer.Plugs.GoogleAuth
end
end
end
但我无法理解它为什么会这样。谁能帮帮我。
更新
添加所有必需的代码。
【问题讨论】:
-
MyApp.Web的内容是什么?上面的代码应该可以正常运行。 -
MyApp.Web 是 phoenix 生成的默认模块(web.ex 文件)。它不包含我添加的任何行。我应该在这里发布整个代码吗?文件有很多行代码,所以我避免在这里粘贴。但我想我错过了粘贴有问题的部分。我将在这里发布 github repo 的链接,而不是在这里粘贴所有内容