Browse files

Allow overridden user models to skip email/password validations condi…

…tionally
  • Loading branch information...
1 parent 857aaa3 commit 6caee9ccd1546786a17cf789dfd756571fe67c0e @jferris jferris committed Feb 17, 2010
Showing with 54 additions and 7 deletions.
  1. +22 −6 lib/clearance/user.rb
  2. +32 −1 test/models/user_test.rb
View
28 lib/clearance/user.rb
@@ -49,12 +49,12 @@ module Validations
# :password must be present, confirmed
def self.included(model)
model.class_eval do
- validates_presence_of :email
- validates_uniqueness_of :email, :case_sensitive => false
- validates_format_of :email, :with => %r{.+@.+\..+}
+ validates_presence_of :email, :unless => :email_optional?
+ validates_uniqueness_of :email, :case_sensitive => false, :allow_blank => true
+ validates_format_of :email, :with => %r{.+@.+\..+}, :allow_blank => true
- validates_presence_of :password, :if => :password_required?
- validates_confirmation_of :password, :if => :password_required?
+ validates_presence_of :password, :unless => :password_optional?
+ validates_confirmation_of :password, :unless => :password_optional?
end
end
end
@@ -165,8 +165,24 @@ def generate_remember_token
self.remember_token = encrypt("--#{Time.now.utc}--#{encrypted_password}--#{id}--#{rand}--")
end
+ # Always false. Override to allow other forms of authentication
+ # (username, facebook, etc).
+ # @return [Boolean] true if the email field be left blank for this user
+ def email_optional?
+ false
+ end
+
+ # True if the password has been set and the password is not being
+ # updated. Override to allow other forms of # authentication (username,
+ # facebook, etc).
+ # @return [Boolean] true if the password field can be left blank for this user
+ def password_optional?
+ encrypted_password.present? && password.blank?
+ end
+
def password_required?
- encrypted_password.blank? || !password.blank?
+ # warn "[DEPRECATION] password_required?: use !password_optional? instead"
+ !password_optional?
end
def send_confirmation_email
View
33 test/models/user_test.rb
@@ -73,7 +73,7 @@ def @user.initialize_salt; end
end
context "When multiple users have signed up" do
- setup { @user = Factory(:user) }
+ setup { Factory(:user) }
should_validate_uniqueness_of :email
end
@@ -221,4 +221,35 @@ def @user.initialize_salt; end
end
+ # optional email/password fields
+ context "a user with an optional email" do
+ setup do
+ @user = User.new
+ class << @user
+ def email_optional?
+ true
+ end
+ end
+ end
+
+ subject { @user }
+
+ should_allow_values_for :email, nil, ""
+ end
+
+ context "a user with an optional password" do
+ setup do
+ @user = User.new
+ class << @user
+ def password_optional?
+ true
+ end
+ end
+ end
+
+ subject { @user }
+
+ should_allow_values_for :password, nil, ""
+ end
+
end

0 comments on commit 6caee9c

Please sign in to comment.