简体   繁体   中英

How to use Rack middleware to simultaneously set cookie and send response with cookie in effect

I'm trying to use Rack Middleware to set a cookie and send a response with the cookie in effect in the same request-response cycle.

Here is the context: I'm working on a website with two modes: a US mode and a UK mode (different logos, navigation bars, styles, etc). When a UK visitor hits the page for the first time, I want to set a 'uk mode' cookie on his browser but also render the UK version of the page. Here is my code so far:

 # middleware/geo_filter_middleware.rb

 def initialize(app)
   @app = app
 end

 def call(env)
   status, headers, body = @app.call(env)
   response = Rack::Response.new(body, status, headers)
   if from_uk?(env)
      response.set_cookie('country', 'UK')
   end
   response.to_a
 end

When a UK visitor hits the page for the first time, it sets the 'uk mode' in their cookie but it still renders the default US version of the page. It's only after the second request when the cookie would come into effect and the UK visitor sees the UK mode.

Does anyone have any idea to simultaneously set the cookie and return a response with the cookie in effect in one request-response cycle?

you need to setup your middleware in your application.rb

config.middleware.insert_before "ActionDispatch::Cookies", "GeoFilterMiddleware"

and in your middleware do something like this:

  def call(env)
    status, headers, body = @app.call(env)
    if from_uk?(env)
      Rack::Utils.set_cookie_header!(headers, 'country', { :value => 'UK', :path => '/'})
    end
    [status, headers, body]
  end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM