Module: ActiveRecord::SecureUuid::ClassMethods

Defined in:
lib/has_secure_uuid.rb

Instance Method Summary collapse

Instance Method Details

#generate_unique_uuidObject



37
38
39
# File 'lib/has_secure_uuid.rb', line 37

def generate_unique_uuid
  SecureRandom.uuid
end

#has_secure_uuid(attribute = :uuid) ⇒ Object

Example using has_secure_uuid

# Schema: User(identifier:string, identifier:string)
class User < ActiveRecord::Base
  has_secure_uuid
  has_secure_uuid :identifier
end

user = User.new
user.save
user.uuid # => "245f9ae1-9f8d-4a0e-817d-8ba3e4d663c1"
user.identifier # => "93712506-fe9e-4ae9-a713-53c67cd9bccc"
user.regenerate_identifier # => true
user.regenerate_uuid # => true

Note that it’s still possible to generate a race condition in the database in the same way that validates_uniqueness_of can. You’re encouraged to add a unique index in the database to deal with this even more unlikely scenario.



28
29
30
31
32
33
34
35
# File 'lib/has_secure_uuid.rb', line 28

def has_secure_uuid(attribute = :uuid)
  define_method("regenerate_#{attribute}") do
    update_attributes attribute => self.class.generate_unique_uuid
  end
  before_create do
    send("#{attribute}=", self.class.generate_unique_uuid) unless send("#{attribute}?")
  end
end