Skip to content

Instantly share code, notes, and snippets.

@ndbroadbent
Created November 30, 2017 13:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ndbroadbent/628ef1d0c044e402d7501fb7373cbaff to your computer and use it in GitHub Desktop.
Save ndbroadbent/628ef1d0c044e402d7501fb7373cbaff to your computer and use it in GitHub Desktop.
UIDs in Rails
module HasUid
extend ActiveSupport::Concern
# Skips characters that look the same, such as 0 and O
UID_CHARS = 'abcdefghjkmnpqrstxyzACDEFGHJKLMNPQRSTXYZ2345679'.split('')
def self.generate_uid(length)
Array.new(length) {
UID_CHARS[SecureRandom.random_number(UID_CHARS.size)]
}.join
end
included do
before_create :set_uid
def set_uid
if uid.blank?
while uid.blank? || self.class.where(uid: uid).exists?
self.uid = [self.class.try(:uid_prefix), HasUid.generate_uid(16)].compact.join('_')
end
end
uid
end
def to_param
uid
end
end
end
class Model < ApplicationRecord
def self.uid_prefix
'mdl'
end
include HasUid
# ...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment