Sha256: 0b1296837de97041415a4501c81e1a5f8a4670724f436cc824391b31bb4d7a20

Contents?: true

Size: 1.42 KB

Versions: 6

Compression:

Stored size: 1.42 KB

Contents

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

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
http-cookie-1.0.0.pre11 lib/http/cookie_jar/yaml_saver.rb
http-cookie-1.0.0.pre10 lib/http/cookie_jar/yaml_saver.rb
http-cookie-1.0.0.pre9 lib/http/cookie_jar/yaml_saver.rb
http-cookie-1.0.0.pre8 lib/http/cookie_jar/yaml_saver.rb
http-cookie-1.0.0.pre7 lib/http/cookie_jar/yaml_saver.rb
http-cookie-1.0.0.pre6 lib/http/cookie_jar/yaml_saver.rb