http-cookie/lib/http/cookie_jar/yaml_saver.rb

57 lines
1.4 KiB
Ruby

require 'http/cookie_jar'
require 'psych' if !defined?(YAML) && RUBY_VERSION == "1.9.2"
require 'yaml'
# YAMLSaver saves and loads cookies in the YAML format.
class HTTP::CookieJar::YAMLSaver < HTTP::CookieJar::AbstractSaver
def save(io, jar)
YAML.dump(@session ? jar.to_a : jar.reject(&:session?), io)
end
def load(io, jar)
begin
data = YAML.load(io)
rescue ArgumentError => e
case e.message
when %r{\Aundefined class/module Mechanize::}
# backward compatibility with Mechanize::Cookie
begin
io.rewind # hopefully
yaml = io.read
# a gross hack
yaml.gsub!(%r{^( [^ ].*:) !ruby/object:Mechanize::Cookie$}, "\\1")
data = YAML.load(yaml)
rescue Errno::ESPIPE
@logger.warn "could not rewind the stream for conversion" if @logger
rescue ArgumentError
end
end
end
case data
when Array
data.each { |cookie|
jar.add(cookie)
}
when Hash
# backward compatibility with Mechanize::Cookie
data.each { |domain, paths|
paths.each { |path, names|
names.each { |cookie_name, cookie_hash|
cookie = HTTP::Cookie.new(cookie_hash)
jar.add(cookie)
}
}
}
else
@logger.warn "incompatible YAML cookie data discarded" if @logger
return
end
end
private
def default_options
{}
end
end