2010-07-20 36 views
9

我正在爲需要有條件地設置cookie的rails應用程序編寫機架中間件組件。我目前正試圖設法設置cookie。從谷歌搜索似乎這應該工作:如何使用(ruby)機架中間件組件設置cookie?

class RackApp 
    def initialize(app) 
    @app = app 
    end 

    def call(env) 
    @status, @headers, @response = @app.call(env) 
    @response.set_cookie("foo", {:value => "bar", :path => "/", :expires => Time.now+24*60*60}) 
    [@status, @headers, @response] 
    end 
end 

它不會給出錯誤,但不設置cookie。我究竟做錯了什麼?

回答

23

如果你想使用Response類,你需要從調用中間件層的結果中進一步實例化它。 此外,您不需要實例變量,像這樣的中間件和可能不想用他們的方式(@狀態等請求送達後會留在周圍的中間件實例)

class RackApp 
    def initialize(app) 
    @app = app 
    end 

    def call(env) 
    status, headers, body = @app.call(env) 
    # confusingly, response takes its args in a different order 
    # than rack requires them to be passed on 
    # I know it's because most likely you'll modify the body, 
    # and the defaults are fine for the others. But, it still bothers me. 

    response = Rack::Response.new body, status, headers 

    response.set_cookie("foo", {:value => "bar", :path => "/", :expires => Time.now+24*60*60}) 
    response.finish # finish writes out the response in the expected format. 
    end 
end 

如果你知道你在做什麼,你可以直接修改cookie頭,如果你不想實例化一個新的對象。

+0

太棒了。這對我來說是完美的。迄今爲止我見過的最清晰的例子。 – phaedryx 2010-07-21 00:34:42

+0

謝謝!五年後,這段代碼正是我所期待的。 – Anurag 2015-03-10 14:39:20

+0

@BaroqueBobcat如果您包括如何直接修改cookie,那將會非常有用。謝謝你的偉大答案! – thesecretmaster 2016-06-22 17:22:44

13

您還可以使用Rack::Utils庫來設置和刪除標題,而不創建Rack :: Response對象。

class RackApp 
    def initialize(app) 
    @app = app 
    end 

    def call(env) 
    status, headers, body = @app.call(env) 

    Rack::Utils.set_cookie_header!(headers, "foo", {:value => "bar", :path => "/"}) 

    [status, headers, body] 
    end 
end