Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails, how can I set a cookie's Max-Age?

In Rails 3.2.8, you can write a cookie like this:

cookies[:login] = {
  :value   => "XJ-122",
  :expires => 1.hour.from_now
}

The docs say that these are the available option symbols:

:value
:path
:domain
:expires
:secure
:httponly

I would expect :max_age to be available as an option too, but perhaps user agent support is not widespread enough yet (?) to warrant including it.

So how should I set a cookie's Max-Age in Rails?

like image 322
GladstoneKeep Avatar asked Dec 07 '25 02:12

GladstoneKeep


1 Answers

I read over the Rails source code for ActionDispatch::Cookies. If you look at how the handle_options method is used you will see that even options not specified in the documentation are passed through. Rails usually passes options around quite liberally, with the philosophy that, somewhere down the line, a method will know what to do with the left-over options.

So, I would suggest that you give it a try with the :max_age option, even though it is not documented, and see what happens.

Note: Rails relies on Rack to set the cookie header, so if for some reason the "Max-Age" "Set-Cookie" header is being passed to Rack but is not being passed through, I would ask over on the Github Rack issue tracker.

Update #1: there has been at least one pull request having to do with Max-Age and Rack, but I'm not sure it is relevant. If the above doesn't work, I think you may want to discuss on the Rack ticket tracker as I mention above.

Update #2: Have you looked at the Rack::Cache middleware? It may be of use.

like image 107
David J. Avatar answered Dec 08 '25 16:12

David J.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!