Reading/writing cookies via a middleware in Rails 4.0

31 views
Skip to first unread message

powi

unread,
Aug 17, 2015, 8:51:38 AM8/17/15
to Ruby on Rails: Talk
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
= Rack::Request.new(env)
     
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


     
@app.call(env)
   
end
 
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.

Elizabeth McGurty

unread,
Aug 17, 2015, 9:22:59 AM8/17/15
to Ruby on Rails: Talk
Check out Rails Internationalization (i18n) API: http://guides.rubyonrails.org/i18n.html.  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..."

Frederick Cheung

unread,
Aug 18, 2015, 2:07:28 AM8/18/15
to Ruby on Rails: Talk
On Monday, August 17, 2015 at 1:51:38 PM UTC+1, powi wrote:
>
> 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.

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.

Fred

Reply all
Reply to author
Forward
0 new messages