简体   繁体   中英

Rails Engine add middleware to host app only

I am developing a gem which is also a Rails::Engine

I would like the engine to add a custom middleware to the host application and I have done that with the following code

module MyModule
  class Engine < ::Rails::Engine
    isolate_namespace MyModule

    initializer "my_gem.middleware" do |app|
      app.config.app_middleware.use "MyModule::MyMiddleware"
    end
  end
end

However this also adds the middleware to those routes defined in the routes.rb file of the Engine. How can I avoid this? I only want the middleware to be added to the host app.

For example, consider the following routes defined in the host application

Rails.application.routes.draw do
  mount MyModule::Engine => "/engine"
  root :to => Proc.new { |env| [200, {'Content-Type' => 'text/html'}, ["Hello World"]] }
end

Everything under /engine should NOT go through MyMiddleware

I am probably going down the wrong path to achieve this and may be I should look at some other solution?

I don't see how you can do that without putting it in the engine. The initializer is run on boot. You could create an URL matcher in your middleware to skip whatever it does if url is /engine. Note that I had to use app.config.middleware.use , not app.config.app_middleware.use

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM