Module: Philiprehberger::HeaderKit::Cookie

Defined in:
lib/philiprehberger/header_kit/cookie.rb

Overview

Parses Cookie headers and builds Set-Cookie header strings.

Class Method Summary collapse

Class Method Details

Build a Set-Cookie header string.

Parameters:

  • name (String)

    cookie name

  • value (String)

    cookie value

  • expires (String, nil) (defaults to: nil)

    Expires attribute value

  • max_age (Integer, nil) (defaults to: nil)

    Max-Age attribute value

  • secure (Boolean) (defaults to: false)

    include Secure flag

  • httponly (Boolean) (defaults to: false)

    include HttpOnly flag

  • samesite (String, nil) (defaults to: nil)

    SameSite attribute (Strict, Lax, None)

  • path (String, nil) (defaults to: nil)

    Path attribute

  • domain (String, nil) (defaults to: nil)

    Domain attribute

Returns:

  • (String)

    formatted Set-Cookie header value



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/philiprehberger/header_kit/cookie.rb', line 41

def self.build_set_cookie(name, value, expires: nil, max_age: nil, secure: false, # rubocop:disable Metrics/ParameterLists
                          httponly: false, samesite: nil, path: nil, domain: nil)
  parts = ["#{name}=#{value}"]
  parts << "Expires=#{expires}" if expires
  parts << "Max-Age=#{max_age}" if max_age
  parts << "Domain=#{domain}" if domain
  parts << "Path=#{path}" if path
  parts << 'Secure' if secure
  parts << 'HttpOnly' if httponly
  parts << "SameSite=#{samesite}" if samesite

  parts.join('; ')
end

.parse(header) ⇒ Hash{String => String}

Parse a Cookie header string into a name-value hash.

Parameters:

  • header (String)

    the Cookie header value

Returns:

  • (Hash{String => String})

    cookie name-value pairs



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/philiprehberger/header_kit/cookie.rb', line 11

def self.parse(header)
  return {} if header.nil? || header.strip.empty?

  cookies = {}

  header.split(';').each do |pair|
    pair = pair.strip
    next if pair.empty?

    name, value = pair.split('=', 2)
    next if name.nil? || name.strip.empty?

    cookies[name.strip] = (value || '').strip
  end

  cookies
end