2012-09-01 26 views
4

在我的Rails 3.2應用程序中,我必須調用某個類類型的中間件實例的方法。如何訪問Rack中間件的特定實例?

我試圖使用Rails.application.middleware但這不起作用,因爲它只包裝中間件而不是它們的實例。

現在我走從Rails.application.app開始使用Ruby的instance_variable_getis_a?,但感覺不對中間件鏈,特別是因爲沒有特定的方式中間件存儲環境。例如Rack::Cache::Context將下一個實例存儲在名爲@backend的變量中,而大多數其他實例則使用@app

有沒有更好的方法來找到中間件實例?

回答

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 
+0

這是從第三方寶石中間件,但由於紅寶石補充說,是沒有問題的:) –

相關問題