Reading/writing cookies via a middleware in Rails 4.0

In my Rails 3.2 setup I had the following middleware:

module Rack class Locale def initialize(app) @app = app end

def call(env)
  request =
  params = request.params
  cookies = request.env['action_dispatch.cookies']
  session = request.env['rack.session']

  requested_locale = params['locale'] || cookies['locale'] || I18n.default_locale

  session['locale'] = cookies['locale'] = locale

end end


It was working fine until I’ve upgraded to Rails 4.0, where cookies is nil and therefore I get the error: NoMethodError: undefined method `’ for nil:NilClass


when cookies['locale'] is called. What’s the proper way to do this in Rails 4.0?

P.S. Rack also was bumped from 1.4.6 to 1.5.5.

Check out Rails Internationalization (i18n) API: Rails Internationalization (I18n) API — Ruby on Rails Guides. Section 2.3: It reads: “You may be tempted to store the chosen locale in a session or a cookie . However, do not do this. The locale should be transparent and a part of the URL…”

The cookies middleware in rails doesn't look like it has changed. However env["actiondispatch.cookies"] is only set lazily - perhaps previously there was some other middleware that was causing it to be set for you? If so then you need to set env["actiondispatch.cookies"] if it is nil

If you create an actiondispatch::request rather than rack::request then you'll get a cookies method on request that does that for you.