Class: Philiprehberger::HttpClient::CookieJar

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/http_client/cookie_jar.rb

Overview

Simple cookie jar that stores cookies across requests within a session. Parses Set-Cookie headers and sends matching cookies back on subsequent requests.

Defined Under Namespace

Classes: Cookie

Instance Method Summary collapse

Constructor Details

#initializeCookieJar

Returns a new instance of CookieJar.



12
13
14
# File 'lib/philiprehberger/http_client/cookie_jar.rb', line 12

def initialize
  @cookies = []
end

Instance Method Details

#clearObject

Remove all stored cookies.



51
52
53
# File 'lib/philiprehberger/http_client/cookie_jar.rb', line 51

def clear
  @cookies.clear
end

Return the Cookie header value for a given URI.

Parameters:

  • uri (URI)

    the request URI

Returns:

  • (String, nil)

    cookie header value or nil if no cookies match



34
35
36
37
38
39
40
# File 'lib/philiprehberger/http_client/cookie_jar.rb', line 34

def cookie_header(uri)
  purge_expired
  matching = @cookies.select { |c| matches?(c, uri) }
  return nil if matching.empty?

  matching.map { |c| "#{c.name}=#{c.value}" }.join('; ')
end

#sizeInteger

Return the number of stored cookies.

Returns:

  • (Integer)


58
59
60
61
# File 'lib/philiprehberger/http_client/cookie_jar.rb', line 58

def size
  purge_expired
  @cookies.size
end

#store(set_cookie_header, request_uri) ⇒ Object

Store cookies from a Set-Cookie response header.

Parameters:

  • set_cookie_header (String)

    the Set-Cookie header value

  • request_uri (URI)

    the URI of the request that received the cookie



20
21
22
23
24
25
26
27
28
# File 'lib/philiprehberger/http_client/cookie_jar.rb', line 20

def store(set_cookie_header, request_uri)
  return unless set_cookie_header

  cookie = parse_set_cookie(set_cookie_header, request_uri)
  return unless cookie

  @cookies.reject! { |c| c.name == cookie.name && c.domain == cookie.domain && c.path == cookie.path }
  @cookies << cookie
end

#to_aArray<Cookie>

Return all stored cookies.

Returns:



45
46
47
48
# File 'lib/philiprehberger/http_client/cookie_jar.rb', line 45

def to_a
  purge_expired
  @cookies.dup
end