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

Returns a new instance of Cookie.



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

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

Instance Attribute Details

#directivesObject (readonly)

Returns the value of attribute directives.



37
38
39
# File 'lib/protocol/http/cookie.rb', line 37

def directives
  @directives
end

#nameObject (readonly)

Returns the value of attribute name.



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

def name
  @name
end

#valueObject (readonly)

Returns the value of attribute value.



36
37
38
# File 'lib/protocol/http/cookie.rb', line 36

def value
  @value
end

Class Method Details

.parse(string) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/protocol/http/cookie.rb', line 68

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

.parse_directives(strings) ⇒ Object



81
82
83
84
85
86
# File 'lib/protocol/http/cookie.rb', line 81

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



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

def encoded_name
  URL.escape(@name)
end

#encoded_valueObject



43
44
45
# File 'lib/protocol/http/cookie.rb', line 43

def encoded_value
  URL.escape(@value)
end

#to_sObject



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

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