How can I specify the order that before_filters are executed?
Ruby on-RailsBefore FilterRuby on-Rails Problem Overview
Does rails make any guarantees about the order that before filters get executed with either of the following usages:
before_filter [:fn1, :fn2]
or
before_filter :fn1
before_filter :fn2
I'd appreciate any help.
Ruby on-Rails Solutions
Solution 1 - Ruby on-Rails
If you refer http://api.rubyonrails.org/v2.3.8/classes/ActionController/Filters/ClassMethods.html, there is a subheading called "Filter chain ordering", here is the example code from that:
class ShoppingController < ActionController::Base
before_filter :verify_open_shop
class CheckoutController < ShoppingController
prepend_before_filter :ensure_items_in_cart, :ensure_items_in_stock
According to the explanation:
> The filter chain for the CheckoutController
is now
> :ensure_items_in_cart
, :ensure_items_in_stock
,
> :verify_open_shop.
So you can explicitly give the order of the filter chain like that.
Solution 2 - Ruby on-Rails
Before_filter Order in Rails http://b2.broom9.com/?p=806
Filter chain ordering http://rails.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html
If you need guarantee order, you may do this:
before_filter :fn3
def fn3
fn1
fn2
end
Solution 3 - Ruby on-Rails
as far as I can tell, you put the first function you want to execute and so forth.
So, something like:
before_filter :fn1, :fn2
def fn1
puts 'foo'
end
def fn2
puts 'bar'
end
Would execute fn1
, then fn2
.
Hope that helps.
Solution 4 - Ruby on-Rails
The filter chain for the CheckoutController
does not follow this order
:ensure_items_in_cart, :ensure_items_in_stock, :verify_open_shop
Instead, it should be
:ensure_items_in_stock, :ensure_items_in_cart, :verify_open_shop