ruby - 如何使用( ruby ) Rack 中间件组件设置 cookie?

标签 ruby cookies rack middleware setcookie

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

最佳答案

如果要使用 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 header 。

关于ruby - 如何使用( ruby ) Rack 中间件组件设置 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3295083/

相关文章:

ruby - 为什么 bundler 看不到自定义的 gem 源?

ruby-on-rails - 如何配置 Heroku Rack/Rails 应用程序来验证传入请求的客户端证书?

ruby-on-rails - 使用 Rack 和 Event Machine 将 WebSockets 与 Rails 集成

ruby-on-rails - 数组到字符串回到数组的转换问题

javascript - Ruby 相当于 JS

ruby - rackup:找不到命令

python - Flask session 不 JSON 序列化 cookie

javascript - Set-Cookie 添加 2 个 cookie

javascript - 如何在 javascript 中创建全局 cookie?

ruby-on-rails - 为安装在 Rails 中的 sinatra 应用程序设计身份验证