CookieJar#parse: Use the block's return values to decide whether to add a cookie.

This commit is contained in:
Akinori MUSHA 2013-04-14 12:10:28 +09:00
parent 5478f3d9c9
commit a1a130f156
2 changed files with 35 additions and 9 deletions

View file

@ -126,10 +126,13 @@ class HTTP::CookieJar
end
include Enumerable
# Parses a Set-Cookie field value `set_cookie` sent from a URI
# `origin` and adds the cookies parsed as valid to the jar. Returns
# an array of cookies that have been added. If a block is given, it
# is called after each cookie is added.
# Parses a Set-Cookie field value `set_cookie` assuming that it is
# sent from a source URL/URI `origin`, and adds the cookies parsed
# as valid and considered acceptable to the jar. Returns an array
# of cookies that have been added.
#
# If a block is given, it is called for each cookie and the cookie
# is added only if the block returns a true value.
#
# `jar.parse(set_cookie, origin)` is a shorthand for this:
#
@ -140,16 +143,15 @@ class HTTP::CookieJar
# See HTTP::Cookie.parse for available options.
def parse(set_cookie, origin, options = nil) # :yield: cookie
if block_given?
HTTP::Cookie.parse(set_cookie, origin, options) { |cookie|
add(cookie)
yield cookie
HTTP::Cookie.parse(set_cookie, origin, options).tap { |cookies|
cookies.select! { |cookie|
yield(cookie) && add(cookie)
}
}
else
HTTP::Cookie.parse(set_cookie, origin, options) { |cookie|
add(cookie)
}
# XXX: ruby 1.8 fails to call super from a proc'ized method
# HTTP::Cookie.parse(set_cookie, origin, options, &method(:add)
end
end

View file

@ -645,6 +645,30 @@ module TestHTTPCookieJar
cookie.domain == cookie.value
}
end
def test_parse
set_cookie = [
"name=Akinori; Domain=rubyforge.org; Expires=Sun, 08 Aug 2076 19:00:00 GMT; Path=/",
"country=Japan; Domain=rubyforge.org; Expires=Sun, 08 Aug 2076 19:00:00 GMT; Path=/",
"city=Tokyo; Domain=rubyforge.org; Expires=Sun, 08 Aug 2076 19:00:00 GMT; Path=/",
].join(', ')
cookies = @jar.parse(set_cookie, 'http://rubyforge.org/')
assert_equal %w[Akinori Japan Tokyo], cookies.map { |c| c.value }
assert_equal %w[Tokyo Japan Akinori], @jar.to_a.sort_by { |c| c.name }.map { |c| c.value }
end
def test_parse_with_block
set_cookie = [
"name=Akinori; Domain=rubyforge.org; Expires=Sun, 08 Aug 2076 19:00:00 GMT; Path=/",
"country=Japan; Domain=rubyforge.org; Expires=Sun, 08 Aug 2076 19:00:00 GMT; Path=/",
"city=Tokyo; Domain=rubyforge.org; Expires=Sun, 08 Aug 2076 19:00:00 GMT; Path=/",
].join(', ')
cookies = @jar.parse(set_cookie, 'http://rubyforge.org/') { |c| c.name != 'city' }
assert_equal %w[Akinori Japan], cookies.map { |c| c.value }
assert_equal %w[Japan Akinori], @jar.to_a.sort_by { |c| c.name }.map { |c| c.value }
end
end
class WithHashStore < Test::Unit::TestCase