Search code examples
rubyrackmiddleware

Rack Middleware in Rack Middleware?


I am trying to build a rack middleware GEM that uses rack middleware itself (RackWired).

I have an existing application, whose config.ru uses Rack::Builder. In that block (Rack::Builder), I would like to specify my middleware, and when it is called to use a third party middleware (rack-cors) inside my own to do some stuff. Confusing I know.

The problem is that Rack::Builder's context is in config.ru and my middleware (RackWired) is thus unable to access it to "use" the third party middleware (rack-cors).

The intent of my effort is here

Is there a way to use middleware within middleware?

Thank you


Solution

  • Right, I'm not entirely sure what you're trying to do. But you can do this

    class CorsWired
      def initialize(app)
        @app = app
      end
    
      def call(env)
        cors = Rack::Cors.new(@app, {}) do
          allow do
            origins '*'
            resource '*', :headers => :any, :methods => [:get, :post, :put, :options, :delete], :credentials => false
          end
        end
        cors.call(env)
      end
    end
    

    Your config.ru should have use CorsWired though, not use CorsWired.new

    This is I think what you were asking but I think you're missing the point of middleware. You should just change your config.ru to use rack-cors before/after your middleware depending on what you want to do.

    require 'rack'
    require 'rack/cors'
    require './cors_wired'      
    
    app = Rack::Builder.new  do
      use Rack::Cors do
        allow do
            origins '*'
            resource '*', :headers => :any, :methods => [:get, :post, :put, :options, :delete], :credentials => false
          end
        end
      use CorsWired
      run lambda { |env| [200, {'Content-Type' => 'text/plain'}, ['OK']] }  
    end
    run app