Allow passing a base time to HTTP::Cookie.parse() via :date.

This commit is contained in:
Akinori MUSHA 2013-03-12 00:47:17 +09:00
parent 6d8fb94f83
commit 7554bffb32
2 changed files with 21 additions and 6 deletions

View file

@ -134,14 +134,22 @@ class HTTP::Cookie
#
# If a block is given, each cookie object is passed to the block.
#
# The cookie's origin URI/URL and a logger object can be passed in
# +options+ with the keywords +:origin+ and +:logger+,
# respectively.
# Available option keywords are below:
#
# * +origin+
# The cookie's origin URI/URL
# * +date+
# The base date used for interpreting Max-Age attribute values
# instead of the current time
# * +logger+
# Logger object useful for debugging
def parse(set_cookie, options = nil, &block)
if options
logger = options[:logger]
origin = options[:origin] and origin = URI(origin)
date = options[:date]
end
date ||= Time.now
[].tap { |cookies|
set_cookie.split(/,(?=[^;,]*=)|,$/).each { |c|
@ -211,7 +219,7 @@ class HTTP::Cookie
cookie.httponly ||= false
# RFC 6265 4.1.2.2
cookie.expires = Time.now + cookie.max_age if cookie.max_age
cookie.expires = date + cookie.max_age if cookie.max_age
cookie.session = !cookie.expires
if origin

View file

@ -178,20 +178,27 @@ class TestHTTPCookie < Test::Unit::TestCase
def test_parse_max_age
url = URI.parse('http://localhost/')
date = 'Mon, 19 Feb 2012 19:26:04 GMT'
epoch, date = 4485353164, 'Fri, 19 Feb 2112 19:26:04 GMT'
base = Time.at(1363014000)
cookie = HTTP::Cookie.parse("name=Akinori; expires=#{date}", :origin => url).first
assert_equal Time.at(1329679564), cookie.expires
assert_equal Time.at(epoch), cookie.expires
cookie = HTTP::Cookie.parse('name=Akinori; max-age=3600', :origin => url).first
assert_in_delta Time.now + 3600, cookie.expires, 1
cookie = HTTP::Cookie.parse('name=Akinori; max-age=3600', :origin => url, :date => base).first
assert_equal base + 3600, cookie.expires
# Max-Age has precedence over Expires
cookie = HTTP::Cookie.parse("name=Akinori; max-age=3600; expires=#{date}", :origin => url).first
assert_in_delta Time.now + 3600, cookie.expires, 1
cookie = HTTP::Cookie.parse("name=Akinori; max-age=3600; expires=#{date}", :origin => url, :date => base).first
assert_equal base + 3600, cookie.expires
cookie = HTTP::Cookie.parse("name=Akinori; expires=#{date}; max-age=3600", :origin => url).first
assert_in_delta Time.now + 3600, cookie.expires, 1
cookie = HTTP::Cookie.parse("name=Akinori; expires=#{date}; max-age=3600", :origin => url, :date => base).first
assert_equal base + 3600, cookie.expires
end
def test_parse_expires_session