Quote / unquote from Elixir

I am trying to write a macro in elixir that creates a Phoenix router and controller that has an action that should send a message to the caller process (by calling it from a test).

Here's the call to the macro:

start_server self(), "TestService", 8080, "/some_action", fn(conn, _) ->
  conn |> text("")
end

      

The problem is that the pid I pass from test is not saved when inside an activity. The line #1

prints the correct pid and the line #2

prints the wrong pid. I'm sure I missed something in quote

/ unquote

, but I can't seem to find what I am doing wrong?

Here's the definition of the macro:

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

      

+3


source to share





All Articles