Class: Cybertrain::CookieJar

Inherits:
Object
  • Object
show all
Defined in:
cybertrain/cookie_jar.rb

Overview

The request’s cookies, from Cybertrain::Controller#cookies. Names are Strings or Symbols; values are Strings. A write takes a String, or a Hash with value: and any of expires: (a Time), max_age: (seconds), path: ("/"), httponly: (true), secure: (Config#session_secure) and same_site: ("Lax").

Examples:

cookies[:theme]                      # => "dark" or nil
cookies[:theme] = "dark"
cookies[:theme] = { value: "dark", expires: Time.current + 365 * 86_400, httponly: false }
cookies.delete(:theme)
cookies.permanent[:remember] = "1"   # 20 years
cookies.signed[:user_id] = user.id.to_s
cookies.encrypted[:card] = "4242"
cookies.permanent.signed[:user_id] = user.id.to_s

Instance Method Summary collapse

Instance Method Details

#[](name) ⇒ String?

The cookie’s value as the request sent it (or as this request wrote it), nil when there is none.

Parameters:

  • name (String, Symbol)

Returns:

  • (String, nil)


100
101
102
# File 'cybertrain/cookie_jar.rb', line 100

def [](name)
  @cookies[name.to_s]
end

#[]=(name, value) ⇒ String

Writes the cookie (see the class comment for the Hash form).

Parameters:

  • name (String, Symbol)
  • value (String, Hash)

Returns:

  • (String) —

    the value written



109
110
111
# File 'cybertrain/cookie_jar.rb', line 109

def []=(name, value)
  assign_cookie(name.to_s, value, PLAIN, false)
end

#delete(name, path: "/") ⇒ String?

Deletes the cookie: a Set-Cookie with an empty value and Max-Age=0 at path. Returns the value it had.

Parameters:

  • name (String, Symbol)
  • path (String) (defaults to: "/") —

    the path it was written with

Returns:

  • (String, nil)


119
120
121
122
123
124
# File 'cybertrain/cookie_jar.rb', line 119

def delete(name, path: "/")
  key = name.to_s
  set_cookie = Cookies.serialize(key, "", path: path, max_age: 0, secure: @secure)
  @response.replace_cookie(key, set_cookie)
  @cookies.delete(key)
end

#encrypted ⇒ EncryptedCookieJar

The jar of encrypted cookies.

Returns:

Raises:

  • (ArgumentError) —

    without SessionStore (no key)



147
148
149
150
# File 'cybertrain/cookie_jar.rb', line 147

def encrypted
  require_cookie_keys!
  EncryptedCookieJar.new(self, false)
end

#permanent ⇒ PermanentCookieJar

The jar whose writes last 20 years (Max-Age=631139040) unless they give expires: or max_age:.

Returns:



130
131
132
# File 'cybertrain/cookie_jar.rb', line 130

def permanent
  PermanentCookieJar.new(self)
end

#signed ⇒ SignedCookieJar

The jar of signed cookies.

Returns:

Raises:

  • (ArgumentError) —

    without SessionStore (no key)



138
139
140
141
# File 'cybertrain/cookie_jar.rb', line 138

def signed
  require_cookie_keys!
  SignedCookieJar.new(self, false)
end