[英]Ruby on Rails and Rails Engine
Can I access main app's ApplicationController in my rails engine? 我可以在Rails引擎中访问主应用程序的ApplicationController吗? I want to apply a filter to my app's ApplicationController through an engine. 我想通过引擎将过滤器应用于应用程序的ApplicationController。 A bit of code will be really helpful. 一点点代码将非常有帮助。
Thanks! 谢谢!
You can always, in your engine, open the ApplicationController
and write whatever filter you want. 您始终可以在引擎中打开ApplicationController
并编写所需的任何过滤器。 This will be used by your main app automatically after the engine has been loaded. 加载引擎后,您的主应用程序会自动使用它。
Example code in your engine for a set_locale
before_filter
: 引擎中用于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
You could isolate the functionality with which you wish to enhance your host application's ApplicationController doing the following: 您可以通过执行以下操作隔离希望增强主机应用程序的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
Using the initializer above, we make sure our Concerns::Filterable
is included every time the application is reloaded in development. 使用上面的初始化程序,我们确保每次在开发中重新加载应用程序时都包含Concerns::Filterable
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.