Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In rails, does a method called in the before filter of a controller run for every action?

Let's say in my rails controller I have a method set_one() that will be called via a before_filter. Does this method get called every single time right before a controller action or is it a one time thing that runs throughout the controller? If it's a onetime thing, then that would mean the instance variables it creates would be available throughout the controller. I thought controller actions are stateless. Does this help bridge the gap if it only gets run once before all actions?

def set_one
 # do really complex processing and set the variable @one. 
 @one = 1;
end

Thanks in advance. :)

like image 743
Horse Voice Avatar asked Mar 21 '23 00:03

Horse Voice


1 Answers

before_filter will call the method for every request to the controller. You can set it to run only for some actions:

before_filter :authorize, :only => :delete

Or even prevent it from running in particular actions:

before_filter :authorize, :except => [:index, :show]

BTW, the new syntax for before_filter is before_action

like image 149
Sergio A. Avatar answered Apr 19 '23 23:04

Sergio A.