gpt4 book ai didi

ruby-on-rails - 如何在 Rails3 应用程序中的所有其他 Controller before_filters 之后在 gem 中附加 before_filter?

转载 作者:数据小太阳 更新时间:2023-10-29 06:50:39 27 4
gpt4 key购买 nike

有一个 gem,它附加一个 before_filter 到 Rails 应用:

class Railtie < Rails::Railtie
initializer "..." do
ActiveSupport.on_load(:action_controller) do
ActionController::Base.send(:include, Filter)

...

module Filter
extend ActiveSupport::Concern

included do
append_before_filter :set_locale
end

def set_locale
....

这是应用程序中的一些 Controller :

class DesktopsController < ApplicationController
before_filter :set_language_in_session

现在的问题是,来自 gem 的 before_filter 被放入来自 DesktopsController 的 before_filter 之前的过滤器链中:

DesktopsController._process_action_callbacks.select { |c| c.kind == :before }.collect { |filter| filter.filter }
=> [
[0] :set_locale,
[1] :set_language_in_session
]

如何将 gem (set_locale) 中的 before_filter 置于所有其他过滤器的之后? secret 可能就在于这一行:

ActiveSupport.on_load(:action_controller) do

但我尝试了不同的库,但没有任何运气......

顺便说一句。这是 full code的 gem 。 Ruby 1.9.2,Rails 3.0.5。

最佳答案

修改 gem 永远不会成功。 gem 被初始化为 rails 进程中的第一件事,因此在任何实际 Controller 启动之前。所以这意味着,无论您做什么, gem 中的过滤器很可能仍然是第一个 gem 。

所以我看到的唯一解决方案是:

  • 在您自己的 Controller 中使用 prepend_before_filter 来执行那些需要在 set_locale 之前进行的操作。
  • 如果您需要显式控制,请使用 skip_before_filter 和显式 before_filter

在 rails 2 应用程序中,我们设计了一个 hack 来确保某些过滤器作为最后一个过滤器运行,方法是覆盖 perform_action_without_filters(参见 Is there a way to force a before_filter to always execute last?),但我们在升级到 rails 时删除了它3.

关于ruby-on-rails - 如何在 Rails3 应用程序中的所有其他 Controller before_filters 之后在 gem 中附加 before_filter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7447381/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com