class Cookie
Represents an individual cookie key-value pair.
Definitions
def initialize(name, value, directives)
Initialize the cookie with the given name, value, and directives.
Signature
-
parameter
name
String
The name of the cookiel, e.g. "session_id".
-
parameter
value
String
The value of the cookie, e.g. "1234".
-
parameter
directives
Hash
The directives of the cookie, e.g.
{"path" => "/"}
.
Implementation
def initialize(name, value, directives)
@name = name
@value = value
@directives = directives
end
attr :name
Signature
-
attribute
String
The name of the cookie.
attr :value
Signature
-
attribute
String
The value of the cookie.
attr :directives
Signature
-
attribute
Hash
The directives of the cookie.
def encoded_name
Encode the name of the cookie.
Implementation
def encoded_name
URL.escape(@name)
end
def encoded_value
Encode the value of the cookie.
Implementation
def encoded_value
URL.escape(@value)
end
def to_s
Convert the cookie to a string.
Signature
-
returns
String
The string representation of the cookie.
Implementation
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
def self.parse(string)
Parse a string into a cookie.
Signature
-
parameter
string
String
The string to parse.
-
returns
Cookie
The parsed cookie.
Implementation
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
def self.parse_directives(strings)
Parse a list of strings into a hash of directives.
Signature
-
parameter
strings
Array(String)
The list of strings to parse.
-
returns
Hash
The hash of directives.
Implementation
def self.parse_directives(strings)
strings.collect do |string|
key, value = string.split("=", 2)
[key, value || true]
end.to_h
end