Sha256: e65e4edf215848456e97971d9b6089eda74d165901ef2a17cc356d385f5019ba

Contents?: true

Size: 1.59 KB

Versions: 2

Compression:

Stored size: 1.59 KB

Contents

module Uuids

  # The model describes uuids assigned to corresponding records.
  # @see http://www.ietf.org/rfc/rfc4122.txt RFC4122 standard.
  # @see https://en.wikipedia.org/wiki/Universally_unique_identifier Wikipedia
  # article.
  #
  # @example
  #   # Creates the uuid
  #   uuid = Uuids::Uuid.create! record: some_record
  #
  #   # Finds a record by uuid
  #   Uuid.find_by_value(uuid.value).record # => some_record
  #
  #   # Reassigns a uuid to another record
  #   uuid.update_attributes! record: another_record
  #
  class Uuid < ActiveRecord::Base
    self.table_name = :uuids_uuids

    # @!attribute [r] value
    # Assigned by default on creation. Cannot be set or edited manually.
    # @return [String] uuid value as defined in RFC4122.

    UUID = /[a-z\d]{8}-[a-z\d]{4}-[a-z\d]{4}-[a-z\d]{4}-[a-z\d]{12}/
    attr_readonly :value
    validates :value, format: { with: UUID }, allow_nil: true

    # @!attribute record
    # @return [ActiveRecord::Base] an object the uuid is assigned to.

    belongs_to :record, polymorphic: true
    validate   :record_present?

    # Callbacks
    after_initialize :set_default_value
    before_destroy   :forbid_destruction

    private

    # Validates record presence with a custom error message.
    def record_present?
      return if record
      errors.add :record, :blank, uuid: value
    end

    # Sets a new value by default
    def set_default_value
      self.value = SecureRandom.uuid unless value
    end

    # Forbids destruction of the record.
    def forbid_destruction
      errors.add :base, :destruction_forbidden
      false
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
uuids-3.0.0 app/models/uuids/uuid.rb
uuids-2.0.0 app/models/uuids/uuid.rb