Set the start date and expiration of Rails cookies

How do I set up a Rails cookie to start and / or expire on a specific date?

+83
ruby-on-rails cookies
Aug 05 '09 at 9:40
source share
3 answers

Excerpts from the Rails 5 documentation :

Cookies are read and written using ActionController # cookies.

Readable cookies are cookies received with the request; recorded cookies will be sent along with the response. Reading a cookie does not return the cookie itself, but only its value.

Writing examples:

# Sets a simple session cookie. # This cookie will be deleted when the user browser is closed. cookies[:user_name] = "david" # Sets a cookie that expires in 1 hour. cookies[:login] = { value: "XJ-122", expires: 1.hour } # Sets a cookie that expires at a specific time. cookies[:login] = { value: "XJ-122", expires: Time.utc(2020, 10, 15, 5) } # Sets a "permanent" cookie (which expires in 20 years from now). cookies.permanent[:login] = "XJ-122" 

[...]

Optional symbols for setting cookies:

  • :expires - The expiration time of this cookie as a Time or ActiveSupport :: Duration object.

[...]

+195
Aug 05 '09 at 9:48
source share

your question may be related to this question: How do I dynamically set the expiration time for a cookie based session in Rails

one of the comments points to outdated slides :

". If you need to set a validity period for sessions across all controllers in your application, just add the following option for your config / initializers / session_store.rb file:

 :expire_after => 60.minutes 

If you need to set different expiration dates in different controllers or actions, use the following code in action or some before_filter:

 request.session_options = request.session_options.dup request.session_options[:expire_after]= 5.minutes request.session_options.freeze 

Duplication of the hash is necessary only because it is already frozen at the same time although the change is the smallest: expire_after is possible and works flawlessly ... "

Hope this helps. :)

+17
Aug 05 '09 at 9:51
source share

It is worth noting that at the moment it is not possible to set the start time for the cookie. The cookie set is always active immediately.

+3
Mar 29 '15 at 16:39
source share



All Articles