Class: Tweakphoeus::CookieJar

Inherits:
Object
  • Object
show all
Includes:
Helpers
Defined in:
lib/tweakphoeus/cookie_jar.rb

Overview

Cookie manager

Instance Method Summary collapse

Methods included from Helpers

#get_domain

Constructor Details

#initializeCookieJar

Returns a new instance of CookieJar.



10
11
12
# File 'lib/tweakphoeus/cookie_jar.rb', line 10

def initialize
  @cookie_jar = {}
end

Instance Method Details

#add_cookies(host, key, value) ⇒ Object



45
46
47
48
49
# File 'lib/tweakphoeus/cookie_jar.rb', line 45

def add_cookies(host, key, value)
  domain = get_domain(host)
  @cookie_jar[domain] ||= {}
  @cookie_jar[domain][key] = value
end


18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/tweakphoeus/cookie_jar.rb', line 18

def cookie_string(url, headers = {})
  domain = get_domain(url)
  headers ||= {}
  cookies = parse_cookie(headers['Cookie'])

  while domain != ''
    @cookie_jar[domain]&.each do |key, value|
      cookies[key] ||= value
    end
    domain = domain.gsub(/^([^.]+\.?)/, '')
  end

  cookies.map { |key, value| "#{key}=#{value}" }.join('; ')
end

#obtain_cookies(response) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/tweakphoeus/cookie_jar.rb', line 33

def obtain_cookies(response)
  set_cookies_field = [response.headers['Set-Cookie']].compact

  set_cookies_field.each do |cookie|
    key, value = cookie.match(/^([^=]+)=(.+)/).to_a[1..]
    domain = cookie.match(/Domain=([^;]+)/)&.at(1)&.gsub(/^\./, '')

    domain = get_domain(response.request.url) if domain.nil
    set_cookie(domain, key, value)
  end
end

#purge_bad_cookies(cookies) ⇒ Object



14
15
16
# File 'lib/tweakphoeus/cookie_jar.rb', line 14

def purge_bad_cookies(cookies)
  cookies.reject { |cookie| cookie.first.last == '""' }
end