2009-09-18 15:03:41 +00:00
|
|
|
module Devise
|
2009-10-09 11:30:25 +00:00
|
|
|
module Models
|
2009-10-09 12:27:44 +00:00
|
|
|
|
|
|
|
# Validatable creates all needed validations for a user email and password.
|
|
|
|
# It's optional, given you may want to create the validations by yourself.
|
|
|
|
# Automatically validate if the email is present, unique and it's format is
|
|
|
|
# valid. Also tests presence of password, confirmation and length
|
2009-10-09 11:30:25 +00:00
|
|
|
module Validatable
|
2009-09-18 15:03:41 +00:00
|
|
|
|
2009-10-12 11:37:28 +00:00
|
|
|
# Email regex used to validate email formats. Retrieved from authlogic.
|
2009-10-09 11:30:25 +00:00
|
|
|
EMAIL_REGEX = /\A[\w\.%\+\-]+@(?:[A-Z0-9\-]+\.)+(?:[A-Z]{2,4}|museum|travel)\z/i
|
2009-09-18 15:03:41 +00:00
|
|
|
|
2009-11-24 15:56:54 +00:00
|
|
|
# All validations used by this module.
|
|
|
|
VALIDATIONS = [ :validates_presence_of, :validates_uniqueness_of, :validates_format_of,
|
|
|
|
:validates_confirmation_of, :validates_length_of ].freeze
|
|
|
|
|
2009-10-09 11:30:25 +00:00
|
|
|
def self.included(base)
|
2009-11-24 15:56:54 +00:00
|
|
|
assert_validations_api!(base)
|
|
|
|
|
2009-10-09 11:30:25 +00:00
|
|
|
base.class_eval do
|
2009-11-15 05:32:22 +00:00
|
|
|
attribute = authentication_keys.first
|
2009-09-18 15:03:41 +00:00
|
|
|
|
2009-11-15 05:32:22 +00:00
|
|
|
validates_presence_of attribute
|
|
|
|
validates_uniqueness_of attribute, :allow_blank => true
|
|
|
|
validates_format_of attribute, :with => EMAIL_REGEX, :allow_blank => true,
|
|
|
|
:scope => authentication_keys[1..-1]
|
2009-09-18 15:03:41 +00:00
|
|
|
|
2009-11-15 05:32:22 +00:00
|
|
|
with_options :if => :password_required? do |v|
|
|
|
|
v.validates_presence_of :password
|
|
|
|
v.validates_confirmation_of :password
|
|
|
|
v.validates_length_of :password, :within => 6..20, :allow_blank => true
|
|
|
|
end
|
2009-10-09 11:30:25 +00:00
|
|
|
end
|
2009-09-18 15:03:41 +00:00
|
|
|
end
|
|
|
|
|
2009-11-24 15:56:54 +00:00
|
|
|
def self.assert_validations_api!(base) #:nodoc:
|
|
|
|
unavailable_validations = VALIDATIONS.select { |v| !base.respond_to?(v) }
|
|
|
|
|
|
|
|
unless unavailable_validations.empty?
|
|
|
|
raise "Could not use :validatable module since #{base} does not respond " <<
|
|
|
|
"to the following methods: #{unavailable_validations.to_sentence}."
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2009-10-20 13:08:40 +00:00
|
|
|
protected
|
2009-09-18 15:03:41 +00:00
|
|
|
|
2009-10-09 11:30:25 +00:00
|
|
|
# Checks whether a password is needed or not. For validations only.
|
2009-10-09 12:27:44 +00:00
|
|
|
# Passwords are always required if it's a new record, or if the password
|
|
|
|
# or confirmation are being set somewhere.
|
2009-10-09 11:30:25 +00:00
|
|
|
def password_required?
|
|
|
|
new_record? || !password.nil? || !password_confirmation.nil?
|
|
|
|
end
|
|
|
|
end
|
2009-09-18 15:03:41 +00:00
|
|
|
end
|
|
|
|
end
|