Rails 4 before_action, pass parameters to invoked method

Ruby

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

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

Solution 2 - Ruby

You can use a lambda:

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

Solution 3 - Ruby

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 - Ruby

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'.

Solution 5 - Ruby

The SupportsController

class SupportsController < ApplicationController    
  before_action only: [:show, :edit, :update, :destroy] { |ctrl|
    ctrl.set_support("the_value")
  }
...

The ApplicationController

class ApplicationController < ActionController
  def set_support (value = "")
    p value
  end
...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionParsaView Question on Stackoverflow
Solution 1 - RubyLinus OleanderView Answer on Stackoverflow
Solution 2 - RubyKyle DecotView Answer on Stackoverflow
Solution 3 - Rubycb24View Answer on Stackoverflow
Solution 4 - RubytihomView Answer on Stackoverflow
Solution 5 - RubyDarlan DieterichView Answer on Stackoverflow