require 'digest/sha1' class User < ActiveRecord::Base # see http://www.regular-expressions.info/email.html EMAIL_REGEXP = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i validates_presence_of :email validates_format_of :email, :with => EMAIL_REGEXP validates_uniqueness_of :email validates_presence_of :hashed_password before_validation :hash_password attr_accessible nil attr_accessor :password class << self def authenticate(username, password) User.first(:conditions => { :email => username, :hashed_password => hash_password(password) }) end def hash_password(password) Digest::SHA1.hexdigest(password) end end private def hash_password if password self[:hashed_password] = self.class.hash_password(password) end end end