views:

1482

answers:

2

Rails cookies,

i need to set start date and expire date using cookie,

for eg., once the added item reaches third day, the item should expire.

+7  A: 

Cookies are read and written through ActionController#cookies.

The cookies being read are the ones received along with the request, the cookies being written will be sent out with the response. Reading a cookie does not get the cookie object itself back, just the value it holds.

Examples for writing:

  # Sets a simple session cookie.
  cookies[:user_name] = "david"

  # Sets a cookie that expires in 1 hour.
  cookies[:login] = { :value => "XJ-122", :expires => 1.hour.from_now }

Examples for reading:

  cookies[:user_name] # => "david"
  cookies.size        # => 2

Example for deleting:

  cookies.delete :user_name

Please note that if you specify a :domain when setting a cookie, you must also specify the domain when deleting the cookie:

 cookies[:key] = {
   :value => 'a yummy cookie',
   :expires => 1.year.from_now,
   :domain => 'domain.com'
 }

 cookies.delete(:key, :domain => 'domain.com')

The option symbols for setting cookies are:

* :value - The cookie’s value or list of values (as an array).
* :path - The path for which this cookie applies. Defaults to the root of the application.
* :domain - The domain for which this cookie applies.
* :expires - The time at which this cookie expires, as a Time object.
* :secure - Whether this cookie is a only transmitted to HTTPS servers. Default is false.
* :httponly - Whether this cookie is accessible via scripting or only HTTP. Defaults to false.
Senthil Kumar Bhaskaran
A: 

your question might be related to this question: How to I dynamically set the expiry time for a cookie-based session in Rails

one of the comments points to Deprecating SlideSessions:

"..If you need to set expiration period for sessions through all controllers in your application, simply add the following option to your config/intializers/session_store.rb file:

:expire_after => 60.minutes

If you need to set different expiration time 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 needed only because it is already frozen at that point, even though modification of at least :expire_after is possible and works flawlessly..."

I hope that helps. :)

pageman