Created
April 29, 2021 10:23
-
-
Save danielpaul/161457dae829f8f7780f6131e353bcb6 to your computer and use it in GitHub Desktop.
Generate Unique User Referral Code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User < ApplicationRecord | |
validates_length_of :first_name, :last_name, minimum: 2 | |
validates :refferal_code, presence: true, uniqueness: true | |
before_validation :set_referral_code | |
private | |
def set_referral_code | |
return true if referral_code.present? | |
referral_code = new_referral_code | |
end | |
def new_referral_code | |
count = 0 | |
token = nil | |
loop do | |
token = (first_name + last_name).upcase[0..2] + rand.to_s[2..5] | |
break if User.where(refferal_code: token).empty? | |
end | |
if count > 5 | |
raise 'Took too long to generate a unique code' | |
end | |
token | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment