我试图在elixir中编写一个宏来创建一个Phoenix路由器和一个控制器,它有一个应该向调用者进程发送消息的动作(从测试中调用它)。
这是对宏的调用:
start_server self(), "TestService", 8080, "/some_action", fn(conn, _) ->
conn |> text("")
end
问题是,当我在行动中时,不会保留从测试中传来的pid。
行#1
打印正确的pid,行#2
打印错误的pid。我很确定我错过了关于quote
/ unquote
的内容,但我无法找到我做错的事情?
这里是宏定义:
defmacro start_server pid, name, port, path, handler do
controller_name = String.to_atom("#{name}Controller")
router_name = String.to_atom("#{name}Router")
quote do
IO.inspect(unquote(pid)) # 1
ctrl = defmodule unquote(controller_name) do
use Phoenix.Controller
def handle conn, msg do
IO.inspect(unquote(pid)) # 2
send unquote(pid), {:request, unquote(path), unquote(name)}
unquote(handler).(conn, msg)
end
end
IO.inspect ctrl
router = defmodule unquote(router_name) do
use Phoenix.Router
post unquote(path), unquote(controller_name), :handle
end
Application.put_env(:phoenix, unquote(router_name),
port: unquote(port),
debug_errors: true
)
IO.inspect router
{:ok, pid} = unquote(router_name).start()
end
end