Add Session#delete, more docs

This commit is contained in:
Mike Perham 2016-06-27 16:24:03 -07:00
parent 94db0c8cb8
commit 46b4dc6524
2 changed files with 21 additions and 0 deletions

View file

@ -7,6 +7,7 @@ describe "Session" do
get "/" do |env| get "/" do |env|
sess = env.session sess = env.session
existing = sess["token"]? existing = sess["token"]?
sess.delete("token")
sid = sess.id sid = sess.id
sess["token"] = "abc" sess["token"] = "abc"
"Hello" "Hello"

View file

@ -3,6 +3,17 @@ require "secure_random"
module Kemal module Kemal
# Kemal's default session is in-memory only and holds simple String values only. # Kemal's default session is in-memory only and holds simple String values only.
# The client-side cookie stores a random ID. # The client-side cookie stores a random ID.
#
# Kemal handlers can access the session like so:
#
# get("/") do |env|
# env.session["abc"] = "xyz"
# uid = env.session["user_id"]?
# end
#
# Note that only String values are allowed.
#
# Sessions are pruned hourly after 48 hours of inactivity.
class Sessions class Sessions
NAME = "SessionId" NAME = "SessionId"
@ -44,6 +55,11 @@ module Kemal
@last_access_at = Time.now.epoch_ms @last_access_at = Time.now.epoch_ms
@store[key] = value @store[key] = value
end end
def delete(key : String)
@last_access_at = Time.now.epoch_ms
@store.delete(key)
end
end end
getter! id : String getter! id : String
@ -76,6 +92,10 @@ module Kemal
STORE[@id]?.try &.[key]? STORE[@id]?.try &.[key]?
end end
def delete(key : String)
STORE[@id]?.try &.delete(key)
end
def self.prune!(before = (Time.now - Kemal::Sessions::TTL).epoch_ms) def self.prune!(before = (Time.now - Kemal::Sessions::TTL).epoch_ms)
Kemal::Sessions::STORE.delete_if { |id, entry| entry.last_access_at < before } Kemal::Sessions::STORE.delete_if { |id, entry| entry.last_access_at < before }
nil nil