Created
June 6, 2022 11:58
-
-
Save tvandervossen/d4b5553e21e76fac650fbc7400526d48 to your computer and use it in GitHub Desktop.
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 MyModel < ApplicationRecord | |
TOKEN_CHARS = 'ybndrfg8ejkmcpqxt1wisza345h769' | |
before_create :generate_token | |
# Generates random token leaving out numbers and letters that might be ambiguous and that might | |
# result in words some people find offensive. | |
def self.typeable_token(length = 8) | |
length.times.map do | |
TOKEN_CHARS[SecureRandom.random_number(TOKEN_CHARS.length)] | |
end.join | |
end | |
private | |
def generate_token | |
# A collision is extremely unlikely, but let’s try up to 4 times in case we’re very lucky. | |
4.times do | |
self.token = self.class.typeable_token | |
break if valid? | |
end | |
end | |
validates :token, uniqueness: true | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment