Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check size of session in rails?

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.

like image 461
Simoroshka Avatar asked Nov 04 '25 16:11

Simoroshka


1 Answers

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
like image 162
Stephen Avatar answered Nov 07 '25 10:11

Stephen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!