File: jar.rb

package info (click to toggle)
ruby-httpx 1.7.2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,816 kB
  • sloc: ruby: 12,209; makefile: 4
file content (95 lines) | stat: -rw-r--r-- 2,220 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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
# frozen_string_literal: true

module HTTPX
  module Plugins::Cookies
    # The Cookie Jar
    #
    # It holds a bunch of cookies.
    class Jar
      using URIExtensions

      include Enumerable

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

      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

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

      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

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

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

        return @cookies.each(&blk) unless 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

      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
    end
  end
end