Skip to content

Instantly share code, notes, and snippets.

@cblunt
Created July 9, 2015 07:09
Show Gist options
  • Select an option

  • Save cblunt/ee25065c1f512ae6066a to your computer and use it in GitHub Desktop.

Select an option

Save cblunt/ee25065c1f512ae6066a to your computer and use it in GitHub Desktop.

Revisions

  1. cblunt created this gist Jul 9, 2015.
    6 changes: 6 additions & 0 deletions model.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,6 @@
    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
    18 changes: 18 additions & 0 deletions uuid_concern.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    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