Class: Hyde::Cookie

Inherits:
Object
  • Object
show all
Defined in:
lib/hyde/util/cookie.rb

Overview

Utility class for handling cookies

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, value, params = {}) ⇒ Cookie

Returns a new instance of Cookie.

Parameters:

  • data (String)

    raw cookie data



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/hyde/util/cookie.rb', line 10

def initialize(key, value, params = {})
  unless key.match? Hyde::Util::HeaderRegexp::COOKIE_KEY
    raise Hyde::ParsingError, "invalid cookie key: #{key}"
  end

  unless value.match? Hyde::Util::HeaderRegexp::COOKIE_VALUE
    raise Hyde::ParsingError, "invalid cookie value: #{value}"
  end

  @key = key
  @value = value
  @params = params
end

Instance Attribute Details

#keyObject

Returns the value of attribute key.



35
36
37
# File 'lib/hyde/util/cookie.rb', line 35

def key
  @key
end

#paramsObject (readonly)

Returns the value of attribute params.



36
37
38
# File 'lib/hyde/util/cookie.rb', line 36

def params
  @params
end

#valueObject

Returns the value of attribute value.



35
36
37
# File 'lib/hyde/util/cookie.rb', line 35

def value
  @value
end

Class Method Details

Create cookie(s) from a "Cookie: " format

Parameters:

  • data (String)

    value part of "Cookie: " header

Returns:



53
54
55
56
57
# File 'lib/hyde/util/cookie.rb', line 53

def self.from_cookie_string(data)
  data.split(";").map do |cookiestr|
    Cookie.new(*cookiestr.split("=").map(&:strip))
  end
end

.from_setcookie_string(data) ⇒ Cookie

Create cookie from a "Set-Cookie: " format

Parameters:

  • data (String)

    value part of "Set-Cookie: " header

Returns:



41
42
43
44
45
46
47
48
# File 'lib/hyde/util/cookie.rb', line 41

def self.from_setcookie_string(data)
  kvpair, params = Hyde::Util::ParserCommon.parse_value(
    data,
    regexp: Hyde::Util::HeaderRegexp::COOKIE_PARAM
  )
  key, value = kvpair.split("=").map(&:strip)
  Cookie.new(key, value, params)
end

Instance Method Details

#to_sString

Convert cookie to "Set-Cookie: " string representation.

Returns:

  • (String)


26
27
28
# File 'lib/hyde/util/cookie.rb', line 26

def to_s
  Hyde::Util.make_value(to_short, @params)
end

#to_shortObject

Convert cookie to "Cookie: " string representation (no params)



31
32
33
# File 'lib/hyde/util/cookie.rb', line 31

def to_short
  "#{key.to_s.strip}=#{value.to_s.strip}"
end