I can't add guard in phoenix 1.3 plugs

I am trying to add a guard to a plug in phoenix 1.3 on Elixir 1.6 with the following piece of code in my router:

plug APIWeb.Plug.EnsureRestricted when action in [:create]

I get the error router.ex:15: undefined function when/2 and I don’t get what is wrong or what I am missing

1 Like

This feature is part of Phoenix.Controller, so you cannot use it outside of your controllers. See https://hexdocs.pm/phoenix/Phoenix.Controller.html#module-guards


I see. Thank you for helping out.

1 Like

The when/1 function is a part of the language rather than part of the controller as far as I’m aware (it is in erlang). I’m not sure your usage is valid anyway (since plug ApiWeb.Plug.EnsureAuthenticated is not a function header) but I do know that when only has an arity of 1 (only takes 1 param) and the above is trying to take two params, you might try adding some parens around action in [:create] and see if that works.

However standard when clauses are used as part of a function header like :

def function() when some_expression do

which could be looked as

def function() when (some_expressions) do

Where some_expression or the result of (some_expressions) evaluates to a boolean value.

1 Like

While when on functions, case patterns, etc is a language feature, when attached to a plug macro is a feature of phoenix.