Skip to content

Instantly share code, notes, and snippets.

@ace-subido
Last active November 29, 2019 04:57
Show Gist options
  • Save ace-subido/96945f20618878a8c78a11a8a4543544 to your computer and use it in GitHub Desktop.
Save ace-subido/96945f20618878a8c78a11a8a4543544 to your computer and use it in GitHub Desktop.
Ruby Snippets
class FindUnique
DEFAULT_MAX_COMBINATIONS = ((CHARACTERS.size ** UNIQUE_LENGTH) * 0.9)
TRY_THRESHOLD = 4
UNIQUE_LENGTH = 6
CHARACTERS = %w[A B C D E F G H I J K L 1 2 3 4 5 6]
def self.call
if Something.count > DEFAULT_MAX_COMBINATIONS
Rails.logger.warn "This app has used more than 90% of the possible " \
"combination of external_id's. Adjust FindUnique's constants"
end
tries = 0
loop do
random_id = generate_random_id
if tries >= TRY_THRESHOLD
# Either throw or increase UNIQUE_LENGTH
throw :unavailable_unique_id
end
if !Something.exists?(external_id: external_id)
something.update_attributes(external_id: external_id)
break
end
tries += 1
end
end
def self.generate_random_id
letters = []
while letters.size < UNIQUE_SIZE
letters << CHARACTERS.sample
end
letters.join
end
private_class_method :generate_random_id
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment