From 208e3ed437133387f69fa3f807577e1ad040a36b Mon Sep 17 00:00:00 2001 From: Eric Hodel Date: Sun, 3 Apr 2011 14:51:04 -0700 Subject: [PATCH] Only cleanup cookies once when adding many cookies from a file. GH #38 --- CHANGELOG.rdoc | 1 + lib/mechanize/cookie.rb | 7 ++----- lib/mechanize/cookie_jar.rb | 24 ++++++++++++------------ 3 files changed, 15 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.rdoc b/CHANGELOG.rdoc index 984f3ed0..0fe0f457 100644 --- a/CHANGELOG.rdoc +++ b/CHANGELOG.rdoc @@ -43,6 +43,7 @@ list. GH#56 * Improved handling of non ASCII-7bit compatible characters in links (only an issue on ruby 1.8). GH #36 + * Loading cookies.txt is faster. GH #38 === 1.0.0 diff --git a/lib/mechanize/cookie.rb b/lib/mechanize/cookie.rb index 0097fd0a..c075dd6a 100644 --- a/lib/mechanize/cookie.rb +++ b/lib/mechanize/cookie.rb @@ -64,11 +64,8 @@ def self.parse(uri, str, log = Mechanize.log) end def expired? - if expires.nil? - false - else - Time.now > expires - end + return false unless expires + Time.now > expires end def to_s diff --git a/lib/mechanize/cookie_jar.rb b/lib/mechanize/cookie_jar.rb index 6067d73f..6dd718d2 100644 --- a/lib/mechanize/cookie_jar.rb +++ b/lib/mechanize/cookie_jar.rb @@ -28,7 +28,7 @@ def add(uri, cookie) @jar[normal_domain][cookie.path] ||= {} @jar[normal_domain][cookie.path][cookie.name] = cookie - cleanup + cookie end @@ -95,7 +95,7 @@ def save_as(file, format = :yaml) # :yaml <- YAML structure. # :cookiestxt <- Mozilla's cookies.txt format def load(file, format = :yaml) - @jar = ::File.open(file) { |f| + @jar = open(file) { |f| case format when :yaml then YAML::load(f) @@ -105,6 +105,10 @@ def load(file, format = :yaml) raise ArgumentError, "Unknown cookie jar file format" end } + + cleanup + + self end # Clear the cookie jar @@ -124,19 +128,14 @@ def load_cookiestxt(io) next if fields.length != 7 expires_seconds = fields[4].to_i - begin - expires = (expires_seconds == 0) ? nil : Time.at(expires_seconds) - rescue - next - # Just in case we ever decide to support DateTime... - # expires = DateTime.new(1970,1,1) + ((expires_seconds + 1) / (60*60*24.0)) - end - next if (expires_seconds != 0) && (expires < now) + expires = (expires_seconds == 0) ? nil : Time.at(expires_seconds) + next if expires and (expires < now) c = Mechanize::Cookie.new(fields[5], fields[6]) c.domain = fields[0] - # Field 1 indicates whether the cookie can be read by other machines at the same domain. - # This is computed by the cookie implementation, based on the domain value. + # Field 1 indicates whether the cookie can be read by other machines at + # the same domain. This is computed by the cookie implementation, based + # on the domain value. c.path = fields[2] # Path for which the cookie is relevant c.secure = (fields[3] == "TRUE") # Requires a secure connection c.expires = expires # Time the cookie expires. @@ -144,6 +143,7 @@ def load_cookiestxt(io) add(FakeURI.new(c.domain), c) end + @jar end