How do you clear a single entry from a ruby on rails session?
-
22-08-2019 - |
Question
In ruby on rails when doing session[:foo] = nil
it leaves an entry named :foo
in the session object. How can you get rid of that single entry from the session object?
Solution
Actually there is a way to get delete a value from the session. Like RichH said the session variable is a CGI::Session instance. When enter something like session[:foo]
it is actually looking that symbol up in a @data
instance variable in the session object. That data variable is a hash.
EDIT: There is a data instance variable in the CGI::Session class. If you go to the docs and look at the source code for the []=
method you'll see that there is a @data
member.
So to delete session[:foo]
all you have to do is access that @data
variable from inside the session
session.data[:foo]
Now to delete it:
session.data.delete :foo
Once you do this the there should be no more foo in your session variable.
OTHER TIPS
It looks like the simplest version works. All stores (Cookie, File, ActiveRecord, ...) use AbstractStore::SessionHash
as the object that contains the data, the different stores provide only the means to load and save the AbstractStore::SessionHash
instances.
AbstractStore::SessionHash
inherits from Hash
, so this defers to the Hash#delete
method:
session.delete(:key_to_delete)
As the Session is a Ruby CGI::Session and not a Hash, calling delete will actually delete session. Delete takes no parameters - this is my you're getting the "wrong number of arguments (1 or 0)" message when you try what hyuan suggests.
The generally accepted way to clear a session entry is with session[:foo] = nil as you suggest. It is far from ideal, but statements like session[:foo].nil? will behave as expected.
I really wish it behaved like a normal Hash ... but it doesn't.