Created
July 9, 2015 07:09
-
-
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
This file contains hidden or 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 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 |
This file contains hidden or 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 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