class Mechanize::CookieJar

Public Instance Methods

load(filename, format = :yaml) click to toggle source
Calls superclass method
# File lib/mechanize/cookie_jar.rb, line 107
def load(filename, format = :yaml)
  return super if format != :yaml

  open(filename) { |io|
    begin
      data = YAML.load(io)
    rescue ArgumentError
      @logger.warn "unloadable YAML cookie data discarded" if @logger
      return
    end

    case data
    when Array
      # Forward compatibility
      data.each { |cookie|
        add(cookie)
      }
    when Hash
      data.each { |domain, paths|
        paths.each { |path, names|
          names.each { |cookie_name, cookie|
            add(cookie)
          }
        }
      }
    else
      @logger.warn "incompatible YAML cookie data discarded" if @logger
      return
    end
  }
end
save(filename, *options) click to toggle source
Calls superclass method
# File lib/mechanize/cookie_jar.rb, line 54
def save(filename, *options)
  opthash = {
    :format => :yaml,
    :session => false,
  }
  case options.size
  when 0
  when 1
    case options = options.first
    when Symbol
      opthash[:format] = options
    else
      opthash.update(options) if options
    end
  when 2
    opthash[:format], options = options
    opthash.update(options) if options
  else
    raise ArgumentError, 'wrong number of arguments (%d for 1-3)' % (1 + options.size)
  end

  return super if opthash[:format] != :yaml

  session = opthash[:session]
  nstore = HashStore.new

  each { |cookie|
    next if !session && cookie.session?

    if cookie.max_age
      cookie = cookie.dup
      cookie.expires = cookie.expires # convert max_age to expires
    end
    nstore.add(cookie)
  }

  yaml = YAML.dump(nstore.instance_variable_get(:@jar))

  # a gross hack
  yaml.gsub!(%r{^(    [^ ].*: !ruby/object:)HTTP::Cookie$}) {
    $1 + 'Mechanize::Cookie'
  }
  yaml.gsub!(%r{^(      expires: )(?:|!!null|(.+?)) *$}) {
    $1 + ($2 ? Time.parse($2).httpdate : '')
  }

  open(filename, 'w') { |io|
    io.write yaml
  }

  self
end