如何设置带有(ruby)机架中间件组件的cookie? [英] How do I set a cookie with a (ruby) rack middleware component?

查看:133
本文介绍了如何设置带有(ruby)机架中间件组件的cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为rails应用程序编写机架中间件组件,需要有条件地设置Cookie。我目前正试图找出设置cookie。从谷歌搜索看起来这应该工作:

I'm writing a rack middleware component for a rails app that will need to conditionally set cookies. I am currently trying to figure out to set cookies. From googling around it seems like this should work:

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。我做错了什么?

which doesn't give errors, but doesn't set a cookie either. What am I doing wrong?

推荐答案

如果你想使用Response类,你需要从调用结果中间件层进一步向下堆栈。
另外,你不需要像这样的中间件的实例变量,并且可能不想使用它们(@ status,etc将在请求被提供后在中间件实例中保留)

If you want to use the Response class, you need to instantiate it from the results of calling the middleware layer further down the stack. Also, you don't need instance variables for a middleware like this and probably don't want to use them that way(@status,etc would stay around in the middleware instance after the request is served)

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头,如果你不想实例化一个新的对象。

If you know what you are doing you could directly modify the cookie header, if you don't want to instantiate a new object.

这篇关于如何设置带有(ruby)机架中间件组件的cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆