This blog is part of our Rails 5.2 series.
In Rails 5.1 we have option to set expiry for cookies.
cookies[:username] = {value: "sam_smith", expires: Time.now + 4.hours}
The above code sets cookie which expires in 4 hours.
The expires option, is not supported for
signed and encrypted cookies.
In other words we are not able to decide on server side when an encrypted or
signed cookie would expire.
From Rails 5.2, we'll be able to set expiry for encrypted and signed cookies as well.
cookies.encrypted[:firstname] = { value: "Sam", expires: Time.now + 1.day }
# sets string `Sam` in an encrypted `firstname` cookie for 1 day.
cookies.signed[:lastname] = {value: "Smith", expires: Time.now + 1.hour }
# sets string `Smith` in a signed `lastname` cookie for 1 hour.
Apart from this, in Rails 5.1, we needed to provide an absolute date/time value for expires option.
# setting cookie for 90 minutes from current time.
cookies[:username] = {value: "Sam", expires: Time.now + 90.minutes}
Starting Rails 5.2, we'll be able to set the expires option by giving a
relative duration as value.
# setting cookie for 90 minutes from current time.
cookies[:username] = { value: "Sam", expires: 90.minutes }
# After 1 hour
> cookies[:username]
> #=> "Sam"
# After 2 hours
> cookies[:username]
> #=> nil
> ~~~

Written byMohit Natoo
Related blogs
- 01Rails 5.2 DSL for configuring Content Security PolicyOctober 23, 2018 · Sushant Mittal
- 02Rails 5.2 stops some raw SQL, prevents SQL injectionsOctober 16, 2018 · Piyush Tiwari
- 03Rails 5.2 added method write_multi to cache storeJuly 3, 2018 · Rohan Pujari
- 04Rails 5.2 uses AES-256-GCM authenticated encryptionJune 26, 2018 · Sushant Mittal