I have a ruby on rails application, where i have multiple session variable, out of which i have a specific array of session variable whose values i want to delete every 10 seconds after they have been added
For example i have a session variable
session[:somename] = ["0","1","2","3"]
Now i want to delete the index of the session variable 10 seconds after they have been added,so 0
should be deleted 10 seconds after its being pushed into the session. Is there a way to do this? Can i explicitly set an expiry time for one session? Or is there a way to achieve this in any other form then using a session?
Any help is appreciated, thanks in advance
The short answer is no.
Per default rails uses a single cookie to store the session as a serialized hash. The cookie itself can have an expiry time at which point the client rejects the entire session cookie and its not sent back to rails. But there is no built in solution to expire a single value in the session.
But if you get a bit creative though you could transform the array into a set of pairs:
t = Time.current.to_i
["0","1","2","3"].map.with_index {|v, i| [v, t + ((i + 1) * 10) ]}
# => [["0", 1597863985], ["1", 1597863995], ["2", 1597864005], ["3", 1597864015]]
The second value is just a unix timestamp of when the value expires. You would then reject the expired values when reading it back in:
Time.now.then { |t| serialized.reject{ |(v, e)| Time.at(e) < t } }