How to access specific instances of rack middleware?

In my Rails 3.2 application, I have to call a method on a middleware instance of a particular class type.

I tried to use Rails.application.middleware , but it does not work because it only wraps middleware classes, not their instances.

Now I go through the middleware chain starting with Rails.application.app using Ruby instance_variable_get and is_a? but that’s not very good, especially because there is no specific way that staging stores the context. For example, Rack::Cache::Context stores the next instance in a variable named @backend , while most others use @app .

Is there a better way to find a middleware instance?

+4
source share
1 answer

You could add middleware to the rack environment, as in this example:

 require 'rack' class MyMiddleware attr_accessor :add_response def initialize app @app = app end def call env env['my_middleware'] = self # <-- Add self to the rack environment response = @app.call(env) response.last << @add_response response end end class MyApp def call env env['my_middleware'].add_response = 'World!' # <-- Access the middleware instance in the app [200, {'Content-Type'=>'text/plain'}, ['Hello']] end end use MyMiddleware run MyApp.new 
+5
source

All Articles