Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Plugs for specific actions in Phoenix

How can I use a plug to specific actions on phoenix. The scenario being want to use a plug for a certain actions, or the opposite, not want to use the plug in a certain actions

like image 402
coderVishal Avatar asked May 28 '16 06:05

coderVishal


People also ask

What is a plug in Phoenix?

A Plug will take connection struct (see Plug. Conn) and return a new struct of the same type. It is this concept that allows you to join multiple plugs together, each with their own transformation on a Conn struct. A plug can be either a function or a module that implements the Plug behaviour.

What is elixir plug?

In the Elixir world, Plug is the specification that enables different frameworks to talk to different web servers in the Erlang VM. If you are familiar with Ruby , Plug tries to solve the same problem that Rack does, just with a different approach.

Is Phoenix a controller?

Phoenix. Controller - functions provided by Phoenix to support rendering, and other Phoenix specific behaviour.


1 Answers

As specified in docs plugs controller docs, we can use guard clauses

plug/2 supports guards, allowing a developer to configure a plug to only run in some particular action

plug :log_message, "before show and edit" when action in [:show, :edit]
plug :log_message, "before all but index" when not action in [:index]
# or
plug :log_message, "before all but index" when action not in [:index]

The first plug will run only when action is show or edit. The second plug will always run, except for the index action.

I found this after bit of searching at this issue. Which lead me to the docs. Hope it helps someone

like image 68
coderVishal Avatar answered Oct 20 '22 07:10

coderVishal