我可以在我的 rails 引擎中访问主应用程序的 ApplicationController 吗?我想通过引擎将过滤器应用于我的应用程序的 ApplicationController。一些代码将非常有帮助。
谢谢!
我可以在我的 rails 引擎中访问主应用程序的 ApplicationController 吗?我想通过引擎将过滤器应用于我的应用程序的 ApplicationController。一些代码将非常有帮助。
谢谢!
您可以随时在引擎中打开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
您可以隔离您希望用来增强主机应用程序的 ApplicationController 的功能,执行以下操作:
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
每次在开发中重新加载应用程序时都包含我们的初始化程序。