Created
May 4, 2017 14:20
-
-
Save benhawker/089ca455262348f33afbf0fca0eda70d to your computer and use it in GitHub Desktop.
Unique codes
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
def generate_coupon_code(user_id) | |
characters = %w(A B C D E F G H J K L M P Q R T W X Y Z 1 2 3 4 5 6 7 8 9) | |
code = '' | |
4.times { code << characters.sample } | |
code << user_id.to_s | |
code | |
end | |
# Simple Ruby approach. | |
codes = [] | |
=> [] | |
codes << generate_coupon_code(123) | |
=> ["R5L6123"] | |
codes << generate_coupon_code(123) | |
=> ["R5L6123", "M6EJ123"] | |
new_code = generate_coupon_code(123) | |
=> "81PR123" | |
codes << new_code if !codes.include?(new_code) | |
=> ["R5L6123", "M6EJ123", "81PR123"] | |
codes << new_code if !codes.include?("R5L6123") | |
=> nil | |
codes | |
=> ["R5L6123", "M6EJ123", "81PR123"] | |
# If you are using ActiveRecord consider using a callback (http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html) | |
# that generates another code in the rare case that it is not unique. | |
class Foo < ActiveRecord::Base | |
validate :code_is_unique | |
private | |
def code_is_unique | |
unless Foo.where(code: code).blank? | |
errors.add(:code, 'This code is not unique. Please try again.') | |
end | |
end | |
end | |
# This could introduce unwated behviour for your users - as they didn't actually create his 'non unique code'. | |
# So perhaps you could run this...(unsure whether this is the best approach though.) | |
# Disclaimer : completely untested! | |
Class Foo < ActiveRecord::Base | |
before_validation :code_is_unique | |
def generate_coupon_code(user_id) | |
characters = %w(A B C D E F G H J K L M P Q R T W X Y Z 1 2 3 4 5 6 7 8 9) | |
code = '' | |
4.times { code << characters.sample } | |
code << user_id.to_s | |
code | |
end | |
private | |
def code_is_unique | |
unless Foo.where(code: code).blank? | |
self.code = generate_coupon_code(user_id) | |
end | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment