Rails 4 before_action, pass parameters to invoked method

I have the following code:

class SupportsController < ApplicationController
  before_action :set_support, only: [:show, :edit, :update, :destroy]
  ....

Is it possible to pass a string to the method set_support to be applied for all 4 view methods? Is it possible to pass a different string to the method set_support for each method in the view?


Solution 1:

before_action only: [:show, :edit, :update, :destroy] do
  set_support("value")
end

Solution 2:

You can use a lambda:

class SupportsController < ApplicationController
  before_action -> { set_support("value") }, 
    only: [:show, :edit, :update, :destroy]
  ...

Solution 3:

A short and one-liner answer (which I personally prefer for callbacks) is:

before_action except:[:index, :show] { method :param1, :param2 }

Another example:

after_filter only:[:destroy, :kerplode] { method2_namey_name(p1, p2) }

Solution 4:

You can pass a lambda to the before_action and pass params[:action] to the set_support method like this:

class SupportsController < ApplicationController
  before_action only: [:show, :edit, :update, :destroy] {|c| c.set_support params[:action]}
  ....

Then the param being sent is one of the strings: 'show', 'edit', 'update' or 'destroy'.