public
Last active

ActiveRecord random unique hash

  • Download Gist
random_attribute.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
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
user.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11
class Post < ActiveRecord::Base
 
include RandomAttribute
before_validation :generate_key, on: :create
 
private
 
def generate_key
generate_unique_random_hex(:key, 32)
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.