GladstoneKeep
GladstoneKeep

Reputation: 3982

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?

Upvotes: 3

Views: 1803

Answers (2)

Noach Magedman
Noach Magedman

Reputation: 2473

TL;DR - Just summarizing all of the above

cookies["foo"] = {value: "bar", max_age: 2.minutes}

Rails has no awareness of :max_age and the option is not documented. However, Rails passes unrecognized options through to the underlying Rack middleware. Rack supports :max_age (underscored) and renders the Set-Cookie header properly.

Upvotes: 0

David J.
David J.

Reputation: 32715

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.

Upvotes: 4

Related Questions