2010-07-20 38 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