Refactored username validations to avoid repeated code
This commit is contained in:
parent
e4fc6e02ed
commit
27b038cd40
|
@ -145,10 +145,7 @@ class Group < ActiveRecord::Base
|
|||
protected
|
||||
|
||||
def name_format_validator
|
||||
validator = UsernameValidator.new(name)
|
||||
unless validator.valid_format?
|
||||
validator.errors.each { |e| errors.add(:name, e) }
|
||||
end
|
||||
UsernameValidator.perform_validation(self, 'name')
|
||||
end
|
||||
|
||||
# hack around AR
|
||||
|
|
|
@ -399,10 +399,7 @@ class User < ActiveRecord::Base
|
|||
end
|
||||
|
||||
def username_format_validator
|
||||
validator = UsernameValidator.new(username)
|
||||
unless validator.valid_format?
|
||||
validator.errors.each { |e| errors.add(:username, e) }
|
||||
end
|
||||
UsernameValidator.perform_validation(self, 'username')
|
||||
end
|
||||
|
||||
def email_confirmed?
|
||||
|
@ -591,17 +588,17 @@ class User < ActiveRecord::Base
|
|||
|
||||
private
|
||||
|
||||
def self.discourse_hub_nickname_operation(&block)
|
||||
if SiteSetting.call_discourse_hub?
|
||||
begin
|
||||
yield
|
||||
rescue DiscourseHub::NicknameUnavailable
|
||||
false
|
||||
rescue => e
|
||||
Rails.logger.error e.message + "\n" + e.backtrace.join("\n")
|
||||
end
|
||||
def self.discourse_hub_nickname_operation
|
||||
if SiteSetting.call_discourse_hub?
|
||||
begin
|
||||
yield
|
||||
rescue DiscourseHub::NicknameUnavailable
|
||||
false
|
||||
rescue => e
|
||||
Rails.logger.error e.message + "\n" + e.backtrace.join("\n")
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# == Schema Information
|
||||
|
|
|
@ -1,4 +1,18 @@
|
|||
class UsernameValidator
|
||||
# Public: Perform the validation of a field in a given object
|
||||
# it adds the errors (if any) to the object that we're giving as parameter
|
||||
#
|
||||
# object - Object in which we're performing the validation
|
||||
# field_name - name of the field that we're validating
|
||||
#
|
||||
# Example: UsernameValidator.perform_validation(user, 'name')
|
||||
def self.perform_validation(object, field_name)
|
||||
validator = UsernameValidator.new(object.send(field_name))
|
||||
unless validator.valid_format?
|
||||
validator.errors.each { |e| object.errors.add(field_name.to_sym, e) }
|
||||
end
|
||||
end
|
||||
|
||||
def initialize(username)
|
||||
@username = username
|
||||
@errors = []
|
||||
|
|
Loading…
Reference in New Issue