Use SignedCookieJar in Rails to set signed cookies

My Rails 3 application’s use case – set a tamper-proof cookie other than the default session cookie (which your Rails app is probably already signing.) Maybe your application does this to track analytics, persistent information for logged out users, etc. Anyhow, it turns out it’s really use to do this using the mechanism Rails itself uses for session cookies.

#small helper method within application controller
def secure_cookies
  request.cookie_jar.signed
end
#then to set a secure cookie...
secure_cookies['analytics'] = "last_visit=12/01/2000"
#and retrieve it on the next request
analytics_info = secure_cookies['analytics']

It took a few minutes of reading through source code to see how ‘signed’ works and how to use it (it creates a new cookie jar with the non-signed cookie jar as a ‘parent’). I was happy to see how easy it was in the end, however, and hope this post saves you some time.