1

How do I store a session variable for a specific time?

Or how to reset a variable after a certain time?

I need to use session.delete ('my_key') 15 seconds after the event.

3
  • Set time in that session. if it valid means use it else remove it.. Commented Aug 6, 2019 at 8:32
  • @VelusamyVenkatraman Time in session for variable, right? How can i do this? Commented Aug 6, 2019 at 8:34
  • 1
    Let's admit that you want to store a value and reuse it later with an expiration verification. You can store a hash in the session like this : session[:my_key] = { value: 'whatever', time: Time.current } then when you will want to check if it's valid you will be able to do something like session.dig(:my_key, :time) > 15.seconds.ago ? what_you_want : session.delete(:my_key) Commented Aug 6, 2019 at 10:10

1 Answer 1

2

By default, Rails will use CookieStore to store the session. This means all of sessions data will be stored in the cookie at the Client side. And, by this way, you can do sth like

session['your_key'] = 'Session Content'
session['your_key_expired_at'] = Time.current + 15.minutes

Then, later (for ex: authenticate_user), you can check

if session['your_key_expired_at'] < Time.current
   session.delete('your_key')
end

If you want the data still available after user closes the app, you can use Cookies, as below

cookies[:your_key] = {:value => "session stuff"}, :expires => 15.minutes.from_now}

You can use signed cookies to encrypt your cookies with the apps secret_token, as using session

cookies.signed[:login] = {:value => @user.id, :expires => 1.day.from_now}

Another option, in order to make it more secure, you can use ActiveRecordStore to manage and store session. You just pass the session id to your client, and you can easily manage your session at sever side because you know its created_at

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.