Can I access main app's ApplicationController in my rails engine? I want to apply a filter to my app's ApplicationController through an engine. A bit of code will be really helpful.
Thanks!
You can always, in your engine, open the ApplicationController
and write whatever filter you want. 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
:
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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.