Home > Net >  How to get cookie value from CGI::Cookie.parse?
How to get cookie value from CGI::Cookie.parse?

Time:12-06

How can I get a reasonable cookie value using only standard libraries from Ruby 2.7? According to the docs, #value is supposed to return a value or a list of values, but clearly it's not the case. c.value returns c

$ docker run --rm -it library/ruby:2.7
irb(main):001:0> require 'cgi'
=> true
irb(main):002:0> c = CGI::Cookie.parse('test=foo')['test']
#<CGI::Cookie: "test=foo; path=">
irb(main):003:0> p c.value
#<CGI::Cookie: "test=foo; path=">
irb(main):004:0> c.equal? c.value
=> true
irb(main):005:0> # Please, what?

Expected result: foo (if www-encoded like foo, I want the decoded result foo).

CodePudding user response:

The parent class of CGI::Cookie is Array. Now we can figure it out:

>> c = CGI::Cookie.parse('test=foo')['test']
=> #<CGI::Cookie: "test=foo; path=">
>> c.size
=> 1
>> c.first
=> "foo"
>> c[0]
=> "foo"
  • Related