4

私の Rails 3.2 アプリケーションでは、特定のクラス タイプのミドルウェア インスタンスでメソッドを呼び出す必要があります。

使用しようとしましたが、インスタンスではなくミドルウェアクラスRails.application.middlewareのみをラップするため、機能しません。

Rails.application.app現在、 Ruby のinstance_variable_getandを使用してミドルウェア チェーンを歩いてis_a?いますが、特にミドルウェアがコンテキストを保存する方法が指定されていないため、それは正しくありません。たとえばRack::Cache::Context、次のインスタンスを呼び出される変数に格納しますが、@backend他のほとんどのインスタンスは を使用します@app

ミドルウェア インスタンスを見つけるより良い方法はありますか?

4

1 に答える 1

5

次の例のように、ミドルウェア自体をラック環境に追加できます。

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
于 2012-09-03T19:35:36.233 に答える