Created
November 30, 2017 13:56
-
-
Save ndbroadbent/628ef1d0c044e402d7501fb7373cbaff to your computer and use it in GitHub Desktop.
UIDs in Rails
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
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 |
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 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