From 2acc80d1926a243714dbe1d7da11add0d9e1cb8f Mon Sep 17 00:00:00 2001 From: Josh Susser and Avdi Grimm Date: Fri, 17 May 2013 15:44:35 -0400 Subject: [PATCH] Various idiomatic User refactorings. --- app/models/user.rb | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/app/models/user.rb b/app/models/user.rb index d798d9793bd..08e419ddb00 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -66,16 +66,14 @@ class User < ActiveRecord::Base end def self.sanitize_username!(name) - name.gsub!(/^[^A-Za-z0-9]+|[^A-Za-z0-9_]+$/, "") - name.gsub!(/[^A-Za-z0-9_]+/, "_") + name.gsub!(/^[^[:alnum:]]+|\W+$/, "") + name.gsub!(/\W+/, "_") end - def self.pad_missing_chars_with_1s!(name) - missing_chars = User.username_length.begin - name.length - name << ('1' * missing_chars) if missing_chars > 0 - end def self.find_available_username_based_on(name) + sanitize_username!(name) + name = rightsize_username(name) i = 1 attempt = name until username_available?(attempt) @@ -100,14 +98,13 @@ class User < ActiveRecord::Base name = Regexp.last_match[2] if ['i', 'me'].include?(name) end - sanitize_username!(name) - pad_missing_chars_with_1s!(name) - - # Trim extra length - name = name[0..User.username_length.end-1] find_available_username_based_on(name) end + def self.rightsize_username(name) + name.ljust(username_length.begin, '1')[0,username_length.end] + end + def self.new_from_params(params) user = User.new user.name = params[:name]