2013-06-06 22:40:10 +08:00
|
|
|
module UserNameSuggester
|
|
|
|
|
2015-03-27 07:10:53 +08:00
|
|
|
def self.suggest(name, allow_username = nil)
|
2013-06-06 22:40:10 +08:00
|
|
|
return unless name.present?
|
|
|
|
name = parse_name_from_email(name)
|
2015-03-27 07:10:53 +08:00
|
|
|
find_available_username_based_on(name, allow_username)
|
2013-06-06 22:40:10 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def self.parse_name_from_email(name)
|
|
|
|
if name =~ User::EMAIL
|
|
|
|
# When 'walter@white.com' take 'walter'
|
|
|
|
name = Regexp.last_match[1]
|
|
|
|
# When 'me@eviltrout.com' take 'eviltrout'
|
|
|
|
name = Regexp.last_match[2] if ['i', 'me'].include?(name)
|
|
|
|
end
|
|
|
|
name
|
|
|
|
end
|
|
|
|
|
2015-03-27 07:10:53 +08:00
|
|
|
def self.find_available_username_based_on(name, allow_username = nil)
|
2014-08-25 16:48:29 +08:00
|
|
|
name = fix_username(name)
|
2013-06-06 22:40:10 +08:00
|
|
|
i = 1
|
|
|
|
attempt = name
|
2015-03-27 07:10:53 +08:00
|
|
|
until attempt == allow_username || User.username_available?(attempt)
|
2013-06-06 22:40:10 +08:00
|
|
|
suffix = i.to_s
|
|
|
|
max_length = User.username_length.end - suffix.length - 1
|
|
|
|
attempt = "#{name[0..max_length]}#{suffix}"
|
|
|
|
i += 1
|
|
|
|
end
|
|
|
|
attempt
|
|
|
|
end
|
|
|
|
|
2014-08-25 16:48:29 +08:00
|
|
|
def self.fix_username(name)
|
|
|
|
rightsize_username(sanitize_username(name))
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.sanitize_username(name)
|
2014-03-19 06:02:33 +08:00
|
|
|
name = ActiveSupport::Inflector.transliterate(name)
|
2014-08-25 16:48:29 +08:00
|
|
|
name = name.gsub(/^[^[:alnum:]]+|\W+$/, "")
|
|
|
|
.gsub(/\W+/, "_")
|
|
|
|
.gsub(/^\_+/, '')
|
2015-09-11 19:23:26 +08:00
|
|
|
.gsub(/[\-_\.]{2,}/, "_")
|
2014-03-19 06:02:33 +08:00
|
|
|
name
|
2013-06-06 22:40:10 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def self.rightsize_username(name)
|
|
|
|
name.ljust(User.username_length.begin, '1')[0, User.username_length.end]
|
|
|
|
end
|
|
|
|
|
2014-03-19 06:02:33 +08:00
|
|
|
end
|