Skip to content

Instantly share code, notes, and snippets.

@tvandervossen
Created June 6, 2022 11:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvandervossen/d4b5553e21e76fac650fbc7400526d48 to your computer and use it in GitHub Desktop.
Save tvandervossen/d4b5553e21e76fac650fbc7400526d48 to your computer and use it in GitHub Desktop.
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