From c4ec1d0fcf9f0b2b8cf8808c681cddc0f4ddb3b4 Mon Sep 17 00:00:00 2001 From: Gerhard Schlager Date: Sun, 21 Feb 2016 23:11:52 +0100 Subject: [PATCH] FIX: Don't suggest invalid username --- lib/user_name_suggester.rb | 11 +++++++++-- spec/components/user_name_suggester_spec.rb | 9 +++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/lib/user_name_suggester.rb b/lib/user_name_suggester.rb index f39565941f0..e809be0b41a 100644 --- a/lib/user_name_suggester.rb +++ b/lib/user_name_suggester.rb @@ -42,14 +42,21 @@ module UserNameSuggester # 2. removes unallowed leading characters name.gsub!(/^\W+/, "") # 3. removes unallowed trailing characters - name.gsub!(/[^A-Za-z0-9]+$/, "") + name = remove_unallowed_trailing_characters(name) # 4. unify special characters name.gsub!(/[-_.]{2,}/, "_") name end + def self.remove_unallowed_trailing_characters(name) + name.gsub!(/[^A-Za-z0-9]+$/, "") + name + end + def self.rightsize_username(name) - name.ljust(User.username_length.begin, '1')[0, User.username_length.end] + name = name[0, User.username_length.end] + name = remove_unallowed_trailing_characters(name) + name.ljust(User.username_length.begin, '1') end end diff --git a/spec/components/user_name_suggester_spec.rb b/spec/components/user_name_suggester_spec.rb index 9d02951cbf3..6046aa6ef7e 100644 --- a/spec/components/user_name_suggester_spec.rb +++ b/spec/components/user_name_suggester_spec.rb @@ -93,6 +93,15 @@ describe UserNameSuggester do it 'should handle typical facebook usernames' do expect(UserNameSuggester.suggest('roger.nelson.3344913')).to eq('roger.nelson.33') end + + it 'removes underscore at the end of long usernames that get truncated' do + expect(UserNameSuggester.suggest('uuuuuuuuuuuuuu_u')).to_not end_with('_') + end + + it "adds number if it's too short after removing trailing underscore" do + User.stubs(:username_length).returns(8..8) + expect(UserNameSuggester.suggest('uuuuuuu_u')).to eq('uuuuuuu1') + end end end