Brian DiCasa
Brian DiCasa

Reputation: 9487

Rails ActionController Execute Same Code for Every Action

To the rails experts out there I was wondering where/how you would execute the same code for every action in your web application? If you can point me to an article or provide a short code snippet I would greatly appreciate it.

Thanks in advance to anyone who can help.

Upvotes: 17

Views: 6324

Answers (3)

Matchu
Matchu

Reputation: 85862

It sounds to me like you're talking about filters.

class MyController < ActionController::Base
  before_filter :execute_this_for_every_action

  def index
    @foo = @bar
  end

  def new
    @foo = @bar.to_s
  end

  def execute_this_for_every_action
    @bar = :baz
  end
end

You can put the filter on the ApplicationController, too, if you want every controller to run it.

Upvotes: 15

Sam Coles
Sam Coles

Reputation: 4043

Use a filter in your ApplicationController to run the code for every action in your application. All your controllers descend from ApplicationController, so putting the filter there will ensure the filter gets run.

class ApplicationController
  before_filter :verify_security_token
  def verify_security_token; puts "Run"; end;
end

Upvotes: 31

westoque
westoque

Reputation: 417

  • before_filter if you want the code to be executed "before" each action.

  • If you want the action to be declared each time you use it, you can put it in ApplicationController and call the method in any controller.

Another approach is to use helpers like:

module PersonHelper
   def eat
     {.. some code ..}
   end
end

And in your controller:

class MyController < ActionController::Base
  include PersonHelper

  def index
     eat
  end
end

Upvotes: 2

Related Questions