Method: Mechanize::CookieJar#save

Defined in:
lib/mechanize/cookie_jar.rb

#save(output, *options) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/mechanize/cookie_jar.rb', line 67

def save(output, *options)
  output.respond_to?(:write) or
    return ::File.open(output, 'w') { |io| save(io, *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(output, opthash) 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 : '')
  }

  output.write yaml

  self
end