Class: Protocol::HTTP::Cookie

Inherits:
Object
  • Object
show all
Defined in:
lib/protocol/http/cookie.rb

Overview

Represents an individual cookie key-value pair.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, value, directives) ⇒ Cookie

Initialize the cookie with the given name, value, and directives.



18
19
20
21
22
# File 'lib/protocol/http/cookie.rb', line 18

def initialize(name, value, directives)
  @name = name
  @value = value
  @directives = directives
end

Instance Attribute Details

#directivesObject (readonly)

Returns the value of attribute directives.



31
32
33
# File 'lib/protocol/http/cookie.rb', line 31

def directives
  @directives
end

#nameObject (readonly)

Returns the value of attribute name.



25
26
27
# File 'lib/protocol/http/cookie.rb', line 25

def name
  @name
end

#The name of the cookie.(nameofthecookie.) ⇒ Object (readonly)



25
# File 'lib/protocol/http/cookie.rb', line 25

attr :name

#The value of the cookie.(valueofthecookie.) ⇒ Object (readonly)



28
# File 'lib/protocol/http/cookie.rb', line 28

attr :value

#valueObject (readonly)

Returns the value of attribute value.



28
29
30
# File 'lib/protocol/http/cookie.rb', line 28

def value
  @value
end

Class Method Details

.parse(string) ⇒ Object

Parse a string into a cookie.



71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/protocol/http/cookie.rb', line 71

def self.parse(string)
  head, *directives = string.split(/\s*;\s*/)
  
  key, value = head.split("=", 2)
  directives = self.parse_directives(directives)
  
  self.new(
    URL.unescape(key),
    URL.unescape(value),
    directives,
  )
end

.parse_directives(strings) ⇒ Object

Parse a list of strings into a hash of directives.



88
89
90
91
92
93
# File 'lib/protocol/http/cookie.rb', line 88

def self.parse_directives(strings)
  strings.collect do |string|
    key, value = string.split("=", 2)
    [key, value || true]
  end.to_h
end

Instance Method Details

#encoded_nameObject

Encode the name of the cookie.



34
35
36
# File 'lib/protocol/http/cookie.rb', line 34

def encoded_name
  URL.escape(@name)
end

#encoded_valueObject

Encode the value of the cookie.



39
40
41
# File 'lib/protocol/http/cookie.rb', line 39

def encoded_value
  URL.escape(@value)
end

#The directives of the cookie.=(directivesofthecookie. = (value)) ⇒ Object



31
# File 'lib/protocol/http/cookie.rb', line 31

attr :directives

#to_sObject

Convert the cookie to a string.



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/protocol/http/cookie.rb', line 46

def to_s
  buffer = String.new.b
  
  buffer << encoded_name << "=" << encoded_value
  
  if @directives
    @directives.collect do |key, value|
      buffer << ";"
      
      case value
      when String
        buffer << key << "=" << value
      when TrueClass
        buffer << key
      end
    end
  end
  
  return buffer
end