Class: MaimaiNet::FaradayExt::CookieJar

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/maimai_net/faraday_ext/cookie_jar.rb

Overview

Slight modification from faraday-cookie_jar to follow domain redirects on response.

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ CookieJar

Returns a new instance of CookieJar.



8
9
10
11
# File 'lib/maimai_net/faraday_ext/cookie_jar.rb', line 8

def initialize(app, options = {})
  super(app)
  @jar = options[:jar] || HTTP::CookieJar.new
end

Instance Method Details

#call(env) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/maimai_net/faraday_ext/cookie_jar.rb', line 13

def call(env)
  cookies = @jar.cookies(env[:url])
  unless cookies.empty?
    cookie_header = {}
    # assign them to dummy cookie to make it compatible
    HTTP::Cookie.parse(env[:request_headers]["Cookie"], env[:url]).each do |cookie|
      cookie_header[cookie.name] = cookie.cookie_value
    end if env[:request_headers]['Cookie']

    cookies.each do |cookie| cookie_header[cookie.name] = cookie.cookie_value end
    env[:request_headers]["Cookie"] = HTTP::Cookie.cookie_value(cookie_header.values)
  end

  @app.call(env).on_complete do |res|
    if set_cookie = res[:response_headers]["Set-Cookie"]
      @jar.parse(set_cookie, res[:url])
    end if res[:response_headers]
  end
end