I want to be able to parse raw cookie strings in ruby 1.9.3p194 (hotfix 2012-04-20 version 35410) [x86_64-darwin10.8.0].
The CGI :: Cookie library looked promising, however it does not work as I thought it might be.
For instance,
CGI::Cookie::parse("ASPSESSIONIDSCDRSRTS=HHALOHOBJGJMLPIANNLDOMCJ; path=/").each_key {|name| p 'Cookie name: ' + name}
Will return:
"Cookie name: ASPSESSIONIDSCDRSRTS" "Cookie name: path"
I would like something like a CGI::new instance to work, except that you pass it a raw cookie string:
cookie1 = CGI::Cookie::new('name' => 'name', 'value' => ['value1', 'value2', ...], 'path' => 'path', # optional 'domain' => 'domain', # optional 'expires' => Time.now, # optional 'secure' => true # optional ) name = cookie1.name values = cookie1.value path = cookie1.path domain = cookie1.domain expires = cookie1.expires secure = cookie1.secure
I cannot figure out how to do this eloquently from the raw cookie line.
EDIT ---
The following code is in the ~/.rvm/src/ruby-1.9.3-p194/lib/cgi/cookie.rb . Therefore, it should return as follows cookies[name] = Cookie::new(name, *values) . It seems like I'm not getting it.
# Parse a raw cookie string into a hash of cookie-name=>Cookie # pairs. # # cookies = CGI::Cookie::parse("raw_cookie_string") # # { "name1" => cookie1, "name2" => cookie2, ... } # def Cookie::parse(raw_cookie) cookies = Hash.new([]) return cookies unless raw_cookie raw_cookie.split(/[;,]\s?/).each do |pairs| name, values = pairs.split('=',2) next unless name and values name = CGI::unescape(name) values ||= "" values = values.split('&').collect{|v| CGI::unescape(v,@@accept_charset) } if cookies.has_key?(name) values = cookies[name].value + values end cookies[name] = Cookie::new(name, *values) end cookies end
EDIT ---
This seems like an error in the Ruby CGI::Cookie.parse . I opened an error report in the Ruby tracker buffer - https://bugs.ruby-lang.org/issues/7364