Created
September 25, 2012 16:31
-
-
Save agibralter/3782982 to your computer and use it in GitHub Desktop.
ActiveRecord random unique hash
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 RandomAttribute | |
def generate_unique_random_base64(attribute, n) | |
until random_is_unique?(attribute) | |
self.send(:"#{attribute}=", random_base64(n)) | |
end | |
end | |
def generate_unique_random_hex(attribute, n) | |
until random_is_unique?(attribute) | |
self.send(:"#{attribute}=", SecureRandom.hex(n/2)) | |
end | |
end | |
private | |
def random_is_unique?(attribute) | |
val = self.send(:"#{attribute}") | |
val && !self.class.send(:"find_by_#{attribute}", val) | |
end | |
def random_base64(n) | |
val = base64_url | |
val += base64_url while val.length < n | |
val.slice(0..(n-1)) | |
end | |
def base64_url | |
SecureRandom.base64(60).downcase.gsub(/\W/, '') | |
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 Post < ActiveRecord::Base | |
include RandomAttribute | |
before_validation :generate_key, on: :create | |
private | |
def generate_key | |
generate_unique_random_hex(:key, 32) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment