1 module ActionController #:nodoc:
2 # Cookies are read and written through ActionController#cookies. The cookies being read are what were received along with the request,
3 # the cookies being written are what will be sent out with the response. Cookies are read by value (so you won't get the cookie object
4 # itself back -- just the value it holds). Examples for writing:
6 # cookies[:user_name] = "david" # => Will set a simple session cookie
7 # cookies[:login] = { :value => "XJ-122", :expires => 1.hour.from_now }
8 # # => Will set a cookie that expires in 1 hour
10 # Examples for reading:
12 # cookies[:user_name] # => "david"
15 # Example for deleting:
17 # cookies.delete :user_name
19 # All the option symbols for setting cookies are:
21 # * <tt>value</tt> - the cookie's value or list of values (as an array).
22 # * <tt>path</tt> - the path for which this cookie applies. Defaults to the root of the application.
23 # * <tt>domain</tt> - the domain for which this cookie applies.
24 # * <tt>expires</tt> - the time at which this cookie expires, as a +Time+ object.
25 # * <tt>secure</tt> - whether this cookie is a secure cookie or not (default to false).
26 # Secure cookies are only transmitted to HTTPS servers.
29 # Returns the cookie container, which operates as described above.
34 # Deprecated cookie writer method
36 response.headers['cookie'] << CGI::Cookie.new(*options)
40 class CookieJar < Hash #:nodoc:
41 def initialize(controller)
42 @controller, @cookies = controller, controller.request.cookies
47 # Returns the value of the cookie by +name+ -- or nil if no such cookie exists. You set new cookies using either the cookie method
48 # or cookies[]= (for simple name/value cookies without options).
50 @cookies[name.to_s].value.first if @cookies[name.to_s] && @cookies[name.to_s].respond_to?(:value)
53 def []=(name, options)
54 if options.is_a?(Hash)
55 options = options.inject({}) { |options, pair| options[pair.first.to_s] = pair.last; options }
56 options["name"] = name.to_s
58 options = { "name" => name.to_s, "value" => options }
64 # Removes the cookie on the client machine by setting the value to an empty string
65 # and setting its expiration date into the past. Like []=, you can pass in an options
66 # hash to delete cookies with extra data such as a +path+.
67 def delete(name, options = {})
68 options.stringify_keys!
69 set_cookie(options.merge("name" => name.to_s, "value" => "", "expires" => Time.at(0)))
73 def set_cookie(options) #:doc:
74 options["path"] = "/" unless options["path"]
75 cookie = CGI::Cookie.new(options)
76 @controller.logger.info "Cookie set: #{cookie}" unless @controller.logger.nil?
77 @controller.response.headers["cookie"] << cookie