I would expect session.size
, session.length
or session.count
to work, but they all return "undefined method". Why, isn't session
a hash?
That was curiosity. The actual question: is there a way to check the size of session in KB? Currently my sessions are stored in cookies and it has a 4 KB limit, and when it exceeds, it simply stops putting new data in there. It would be nice to know when in happens, to reset the session or remove old data.
Following is how rails get the session size:
Firstly, get the session data, see (gems/rack/lib/rack/session/abstract/id.rb:352 commit_session)
data = session.to_hash.delete_if { |k,v| v.nil? }
Then it will encrypt the data, see (gems/actionpack/lib/action_dispatch/middleware/cookies.rb:640):
data = @encryptor.encrypt_and_sign(serialize(name, data))
Lastly, get the bytes:
data.bytesize
You can directly get the session data
but it's hard to encrypt it manually. I usually add a log at the gem code to check the data:
options[:value] = @encryptor.encrypt_and_sign(serialize(name, options[:value]))
puts options[:value].bytesize
raise CookieOverflow if options[:value].bytesize > MAX_COOKIE_SIZE