Class: Protocol::HTTP::Cookie

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

Overview

Represents an individual cookie key-value pair.

Constant Summary collapse

/\A#{TOKEN}\z/.freeze
/\A[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*\z/.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, value, directives = nil) ⇒ Cookie

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



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/protocol/http/cookie.rb', line 29

def initialize(name, value, directives = nil)
  unless VALID_COOKIE_KEY.match?(name)
    raise ArgumentError, "Invalid cookie name: #{name.inspect}"
  end
  
  if value && !VALID_COOKIE_VALUE.match?(value)
    raise ArgumentError, "Invalid cookie value: #{value.inspect}"
  end
  
  @name = name
  @value = value
  @directives = directives
end

Instance Attribute Details

#directivesObject

Returns the value of attribute directives.



50
51
52
# File 'lib/protocol/http/cookie.rb', line 50

def directives
  @directives
end

#nameObject

Returns the value of attribute name.



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

def name
  @name
end

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



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

attr_accessor :name

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



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

attr_accessor :value

#valueObject

Returns the value of attribute value.



47
48
49
# File 'lib/protocol/http/cookie.rb', line 47

def value
  @value
end

Class Method Details

.parse(string) ⇒ Object

Parse a string into a cookie.



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

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

.parse_directives(strings) ⇒ Object

Parse a list of strings into a hash of directives.



91
92
93
94
95
96
# File 'lib/protocol/http/cookie.rb', line 91

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

Instance Method Details

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



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

attr_accessor :directives

#to_sObject

Convert the cookie to a string.



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/protocol/http/cookie.rb', line 55

def to_s
  buffer = String.new
  
  buffer << @name << "=" << @value
  
  if @directives
    @directives.each do |key, value|
      buffer << ";"
      buffer << key
      
      if value != true
        buffer << "=" << value.to_s
      end
    end
  end
  
  return buffer
end