Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you clear a single entry from a ruby on rails session?

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?

like image 475
Jim Soho Avatar asked Mar 26 '09 03:03

Jim Soho


People also ask

How do you destroy a session in rails?

To clear the whole thing use the reset_session method in a controller. Resets the session by clearing out all the objects stored within and initializing a new session object. Good luck!

Where does rails store session data?

By default rails uses cookies to store the session data. All data is stored in the client, not on the server.

What is session in Ruby on Rails?

Rails session is only available in controller or view and can use different storage mechanisms. It is a place to store data from first request that can be read from later requests.

How do you create a session in Ruby?

The rails way of creating a session is just using 'session[:user_id] = user.id'. This will create a session with the user_id. The current_user method will return the current user if there is one or if there is a session present. That means if a user is logged in, the current user will be the that user.


2 Answers

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) 
like image 135
Daniel Beardsley Avatar answered Sep 19 '22 21:09

Daniel Beardsley


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.

like image 30
vrish88 Avatar answered Sep 19 '22 21:09

vrish88