【问题标题】:How to access specific instances of the Rack middlewares?如何访问 Rack 中间件的特定实例?
【发布时间】:2012-09-01 12:18:13
【问题描述】:

在我的 Rails 3.2 应用程序中,我必须在某个类类型的中间件实例上调用方法。

我尝试使用Rails.application.middleware,但这不起作用,因为它只包装了中间件,而不是它们的实例。

现在我正在使用 Ruby 的 instance_variable_getis_a?Rails.application.app 开始遍历中间件链,但这感觉不对,特别是因为没有指定的中间件存储上下文的方式。例如Rack::Cache::Context 将下一个实例存储在名为@backend 的变量中,而大多数其他实例使用@app

有没有更好的方法来查找中间件实例?

【问题讨论】:

    标签: ruby-on-rails rack


    【解决方案1】:

    您可以让中间件将自身添加到机架环境中,如下例所示:

    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
    

    【讨论】:

    • 它是来自第 3 方 gem 的中间件,但感谢 Ruby 的加入,这没问题 :)
    猜你喜欢
    • 2012-10-28
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 2019-11-30
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    相关资源
    最近更新 更多