0

我可以在我的 rails 引擎中访问主应用程序的 ApplicationController 吗?我想通过引擎将过滤器应用于我的应用程序的 ApplicationController。一些代码将非常有帮助。

谢谢!

4

2 回答 2

0

您可以随时在引擎中打开ApplicationController并编写您想要的任何过滤器。加载引擎后,您的主应用程序将自动使用它。

引擎中的示例代码set_locale before_filter

class ApplicationController < ActionController::Base
  before_filter :set_locale

  def set_locale
    I18n.locale = params[:locale] if params[:locale].present?
  end
end
于 2013-07-26T14:08:09.013 回答
0

您可以隔离您希望用来增强主机应用程序的 ApplicationController 的功能,执行以下操作:

  1. 创建一个具有过滤器方法的控制器关注点。

Create app/controllers/concerns/filterable.rb

module Concerns::Filterable
  include ActiveSupport::Concern

  included do
    before_filter :do_something
  end

  module InstanceMethods
    def do_something
    end
  end
end

Create config/initializers/filterable.rb

Rails.application.config.to_prepare do
  ApplicationController.send :include, Concerns::Filterable if defined ApplicationController
end

使用上面的初始化程序,我们确保Concerns::Filterable每次在开发中重新加载应用程序时都包含我们的初始化程序。

于 2014-11-15T10:40:18.753 回答