Search code examples
ruby-on-railsrackmiddleware

Swap RAILS middleware before initialized


Let's say this is my RAILS middleware stack after the app is completely booted up:

> Rails.application.middleware

#<ActionDispatch::MiddlewareStack:0x007f9d1636e970
 @middlewares=
  [FooMiddleware,
   ...
   ...
   ...
   SomeEngine::SomeMiddleware]>

Before the initialization process finishes and the middleware stack is frozen, I need to swap SomeEngine::SomeMiddleware with MyProxyMiddleware.

How do you delay inserting or swapping a middleware until all other initializations have been completed, from both the application and the engines it incorporates?

I can't find a place to hook into where the middleware stack is unfrozen but all SomeEngine has been initialized.

If it matters, this is on RAILS 4.2.

Thanks!


Solution

  • Figured it out:

    # config/application.rb
    
    module MyApplication
      class Application < Rails::Application
        # ...
    
        initializer :foo do |app|
          app.middleware.swap SomeEngine::SomeMiddleware, BarMiddleware
        end
      end
    end
    

    Hope this helps other people. Cheers.