RSS
15 May 2007

Rails User Sessions: Remember Me for 2 Weeks!

Author: ceefour | Filed under: Ajax, Opinions, Rails, Ruby, Tips, Web 2.0

You must have grown tired of seeing those “Remember me for two weeks” check box on every web site’s login form. Ever wonder how to do that in Ruby on Rails?

It turns out, you can make use of ActionController’s session management methods for this purpose:

  • Set ::ActionController::Base.session_options[:session_expires] to the maximum amount of time to remember the session
  • Call reset_session whenever the user logs out

Here’s a complete source code for of controller that does exactly this (and only this):

class MainController < ApplicationController

  def index
    render :inline => %Q{
<%= h(flash[:notice]) %><br/>
<% if session[:me] %>
  You are logged on as <%=h (session[:me]) %>. <%= button_to 'Logout', {:action => 'logout'} %>
<% else %>
  <% form_tag({:action => 'login'}) do %>
    Please login: <%= text_field_tag 'username' %>
    <label for="remember"><%= check_box_tag 'remember' %> Remember me</label>
    <%= submit_tag %>
  <% end %>
<% end %>
    }
  end

  def login
    ::ActionController::Base.session_options[:session_expires] =
      params[:remember] ? 2.weeks.from_now : nil
    session[:me] = params[:username]
    flash[:notice] = 'Login successful.'
    redirect_to :action => 'index'
  end

  def logout
    reset_session
    flash[:notice] = 'You have logged out'
    redirect_to :action => 'index'
  end

end

To try the above application, create a skeleton Rails application (e.g. by running rails myapp) then put the above code into app/controllers/main_controller.rb. Run the script/server script then you should be able to check it out by browsing http://localhost:3000/main.

Sweet! icon smile Rails User Sessions: Remember Me for 2 Weeks!

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

  • http://www.carbondiet.org James Smith

    Does this work for you in production mode? I’ve got it working happily in development, but in production it never sets the cookie expiry time…

  • JJS

    James you are right… this cannot work in production. it works perfectly only in development mode.

  • http://edseek.com/ Jason Boxman

    For production you probably want Proc.new { 2.weeks.from_now }.call instead.

    Good luck!