如何使用(ruby)机架中间件组件设置cookie?

时间:2010-07-20 23:04:36

标签: ruby cookies rack middleware setcookie

我正在为需要有条件地设置cookie的rails应用程序编写机架中间件组件。我目前正在试图设置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。我做错了什么?

2 个答案:

答案 0 :(得分:23)

如果要使用Response类,则需要从在堆栈中进一步调用中间件层的结果中实例化它。 此外,您不需要像这样的中间件的实例变量,并且可能不希望以这种方式使用它们(@ status等在请求被提供后将保留在中间件实例中)

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标头,如果您不想实例化新对象。

答案 1 :(得分:16)

您也可以使用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