Class: HTTPX::Plugins::Cookies::Jar

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/httpx/plugins/cookies/jar.rb

Overview

The Cookie Jar

It holds a bunch of cookies.

Instance Method Summary collapse

Constructor Details

#initialize(cookies = nil) ⇒ Jar

Returns a new instance of Jar.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/httpx/plugins/cookies/jar.rb', line 18

def initialize(cookies = nil)
  @cookies = []

  cookies.each do |elem|
    cookie = case elem
             when Cookie
               elem
             when Array
               Cookie.new(*elem)
             else
               Cookie.new(elem)
    end

    @cookies << cookie
  end if cookies
end

Instance Method Details

#[](uri) ⇒ Object



53
54
55
# File 'lib/httpx/plugins/cookies/jar.rb', line 53

def [](uri)
  each(uri).sort
end

#add(cookie, path = nil) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/httpx/plugins/cookies/jar.rb', line 41

def add(cookie, path = nil)
  c = cookie.dup

  c.path = path if path && c.path == "/"

  # If the user agent receives a new cookie with the same cookie-name, domain-value, and path-value
  # as a cookie that it has already stored, the existing cookie is evicted and replaced with the new cookie.
  @cookies.delete_if { |ck| ck.name == c.name && ck.domain == c.domain && ck.path == c.path }

  @cookies << c
end

#each(uri = nil, &blk) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/httpx/plugins/cookies/jar.rb', line 57

def each(uri = nil, &blk)
  return enum_for(__method__, uri) unless blk

  return @cookies.each(&blk) unless uri

  uri = URI(uri)

  now = Time.now
  tpath = uri.path

  @cookies.delete_if do |cookie|
    if cookie.expired?(now)
      true
    else
      yield cookie if cookie.valid_for_uri?(uri) && Cookie.path_match?(cookie.path, tpath)
      false
    end
  end
end

#initialize_dup(orig) ⇒ Object



13
14
15
16
# File 'lib/httpx/plugins/cookies/jar.rb', line 13

def initialize_dup(orig)
  super
  @cookies = orig.instance_variable_get(:@cookies).dup
end

#merge(other) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/httpx/plugins/cookies/jar.rb', line 77

def merge(other)
  cookies_dup = dup

  other.each do |elem|
    cookie = case elem
             when Cookie
               elem
             when Array
               Cookie.new(*elem)
             else
               Cookie.new(elem)
    end

    cookies_dup.add(cookie)
  end

  cookies_dup
end

#parse(set_cookie) ⇒ Object



35
36
37
38
39
# File 'lib/httpx/plugins/cookies/jar.rb', line 35

def parse(set_cookie)
  SetCookieParser.call(set_cookie) do |name, value, attrs|
    add(Cookie.new(name, value, attrs))
  end
end