Read more

Do not try to "slice" on an ActionController::CookieJar

Arne Hartherz
July 15, 2013Software engineer at makandra GmbH

The cookies object in your controllers and views is a ActionController::CookieJar and even though that class inherits from Hash and often behaves like one, you can not call slice on it to select only a subset of cookies. Why? Because Hash#slice calls self.class.new -- which in case of a CookieJar just won't work.

Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

Unfortunately, you can't even say cookies.to_hash and slice on that, just because CookieJar#to_hash is inherited from Hash and will just return self. Bummer.

You need to do it yourself, for example by using collect_hash:

my_keys = %w[ foo bar baz ]
my_cookies = my_keys.collect_hash { |key| [ key, cookies[key] ] }
Posted by Arne Hartherz to makandra dev (2013-07-15 15:13)