Ruby-on-rails 如何指定 before_filters 的执行顺序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5711797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I specify the order that before_filters are executed?
提问by James
Does rails make any guarantees about the order that before filters get executed with either of the following usages:
rails 是否对使用以下任一用法执行过滤器之前的顺序做出任何保证:
before_filter [:fn1, :fn2]
or
或者
before_filter :fn1
before_filter :fn2
I'd appreciate any help.
我很感激任何帮助。
回答by Johnny Woo
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:
如果您参考http://api.rubyonrails.org/v2.3.8/classes/ActionController/Filters/ClassMethods.html,则有一个名为“过滤器链排序”的副标题,这是其中的示例代码:
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
CheckoutControlleris now:ensure_items_in_cart,:ensure_items_in_stock,:verify_open_shop.
的过滤器链
CheckoutController现在是:ensure_items_in_cart,:ensure_items_in_stock,:verify_open_shop.
So you can explicitly give the order of the filter chain like that.
所以你可以像这样明确地给出过滤器链的顺序。
回答by Sector
Before_filter Order in Rails http://b2.broom9.com/?p=806
Rails 中的 Before_filter 顺序 http://b2.broom9.com/?p=806
Filter chain ordering http://rails.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html
过滤器链排序 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
回答by Christian Fazzini
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.
会执行fn1,然后fn2。
Hope that helps.
希望有帮助。
回答by HEraju
The filter chain for the CheckoutControllerdoes not follow this order
的过滤器链CheckoutController不遵循此顺序
: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

