Ruby on Rails Tutorial – Exercise in Chapter 9.6.2 Rails Session

31st mag 2011Ruby on Rails, , ,

Here is the solution to Chapter 9.6 Exercise 2 from Rails Tutorial (the best reference I found so far to start programming Ruby on Rails).

The exercise asks us to:

Use session instead of cookies so that users are automatically signed out when they close their browsers. Hint: Do a Google search on “Rails session”.

First of all, if you are using git for version control, you can create a new dedicated branch:

$ git checkout -b exercise962

Then we make sure all test are green by:

$ bundle exec rspec spec/

The on-line references I suggest you to study about “Rails Session” are this one: http://railscasts.com/episodes/250-authentication-from-scratch and this one: http://wiki.rubyonrails.org/howtos/authentication-authorization

The off-line reference, instead, is the “The Rails 3 way” chapter about sessions.

Applying what you’ll have learned about rails session to the context of the Rails tutorial exercise, eventually you’ll came up with this revisited session_helper.rb file, which is the only one to edit to solve exercise 9.6.2:

module SessionsHelper

def sign_in(user)
#cookies.permanent.signed[:remember_token] = [user.id, user.salt]
session[:user_id] = user.id
self.current_user = user
end

def sign_out
#cookies.delete(:remember_token)
session[:user_id] = nil
self.current_user = nil
end

def current_user=(user)
@current_user = user
end

def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
#@current_user ||= user_from_remember_token
end

def signed_in?
!current_user.nil?
end

private

#def user_from_remember_token
#    User.authenticate_with_salt(*remember_token)
#end

#def remember_token
#    cookies.signed[:remember_token] || [nil, nil]
#end

end

After this changes we can verify that the tests are still green:

$ bundle exec rspec spec/

We can also start the server (with “$ rails s”) and verify the functioning of our brand new session without cookies (we should be logged out every time we close the browser*).

then we can commit the changes

$ git add .

$ git commit -m “Exercise9.6.2 done”

and finally come back to master branch

$ git checkout master

than we can eventually merge the exercise9-6-2 in the master branch if we prefer to avoid using cookies.

$ git merge exercise962

exit.

*Actually, you can test the difference between the cookies and the session versions only in a production environment (e.g. heroku) since every cookie written by localhost (development environment) will expire at the end of the session.

PS: to solve the advanced Exercise 9.6.3 about HTTPS, you can look up here: https://github.com/technicalpickles/ssl_requirement

…and here: http://blog.aisleten.com/2008/06/02/beware-of-ssl_requirement/