Skip to content

Instantly share code, notes, and snippets.

@cblunt
Created July 9, 2015 07:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cblunt/ee25065c1f512ae6066a to your computer and use it in GitHub Desktop.
Save cblunt/ee25065c1f512ae6066a to your computer and use it in GitHub Desktop.
A tiny concern for generating a UUID for a model. Code heavily based off Rails' `has_secure_token` method
class Model < ActiveRecord::Base
include UuidConcern
# uuid attribute is `:uuid` by default. Optionally pass in attribute name, e.g `has_uuid :unique_token`
has_uuid
end
module UuidConcern
extend ActiveSupport::Concern
included do
def self.has_uuid(attribute: :uuid)
# Load securerandom only when has_secure_token is used.
require 'active_support/core_ext/securerandom'
define_method("regenerate_#{attribute}") { update! attribute => self.class.generate_uuid }
before_create { self.send("#{attribute}=", self.class.generate_uuid) unless self.send("#{attribute}?")}
end
private
def self.generate_uuid
SecureRandom.uuid
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment