Owen
Owen

Reputation: 7098

Cant use plug in using macro elixir

So phoenix there are a few plugs I would like to put into a mixed in base_controller.ex but i.e.

plug :xxx when action in [:xxx]

However when I add this to a __using__ macro action seems to be undefined i.e.

defmacro __using__(opts) do
  quote do
    use XXX.Web, :controller
    plug :xxx when action in [:xxx]
  end
end

Results in:

unknown variable action or cannot invoke local action/0 inside guard

Seems like action comes from use XXX.Web, :controller so I am unsure why it is undefined. Any ideas here?

Chris

Upvotes: 1

Views: 74

Answers (1)

Dogbert
Dogbert

Reputation: 222388

The error message could be better, but this seems to be due to Macro hygiene, which is renaming action before sending it to the plug macro. We can disable hygiene on the variable action using Kernel.var!/1. The following works for me:

quote do
  use XXX.Web, :controller
  plug :xxx when var!(action) in [:xxx]
end

Upvotes: 2

Related Questions