So last week we had to give a talk on an aspect of Rails 4 – because I was curious about sessions, I gave a talk on sessions. And now I bring the non-wisdom that was shared there to you, here.
Rails provides an easy to use sessions hash (or something like a hash… an approximate hash. For our purposes it’s a hash.) Just like in Sinatra, you set this value in the controller – it’s the same deal in rails.
– pretend im in a users controller and some great person just signed in: session[:user_id] = current_user.id
The main difference between cookies and sessions is that you explicitly set the expiration dates of cookies like so:
cookies[:name] = { :value => “cookies YUM”, :expires => Time.now + 3600}
Whereas sessions end when the browser is closed or if the user logs out.
Rails 4 encrypts values in the sessions (kind of) hash using a secret token and a secret key base. Rails 3 and below only had a secret token (apparently the level of secrecy wasnt high enough.) The secret token is in config/initializers/secret_token.rb – if your token is compromised you can generate a new one via a custom rake task (rake secret) or by requiring ‘securerandom’ and then using SecureRandom.hex(64).
You can also store short messages to flash to the user in another fake hash but that isn’t what this talk was about so maybe read about that on your own time.
You can’t store more than 4kb in a session, flash or cookie. Although if you do this with a cookie (from what I heard it’s kind of tough) you get an extremely enviable cookie overflow error.
And that’s what I know about sessions. I know a lot more about cookies but mostly because that phrase has more than one meaning.