Sha256: 5d2a26820750f98484aee88e85523c9d72494fed9748cbc18bd7f678108f6369

Contents?: true

Size: 1.3 KB

Versions: 3

Compression:

Stored size: 1.3 KB

Contents

module Uuids

  # Stores uuids assigned to corresponding records.
  #
  # == Attributes:
  #
  # +value+:: A value of uuid as defined in
  #           {RFC4122}[http://www.ietf.org/rfc/rfc4122.txt].
  #           Assigned by default on creation. Cannot be set or edited manually.
  # +record+:: An AR record the uuid is assigned to.
  #            Required attribute. Can be changed.
  #
  # == Examples:
  #
  #     # Create the uuid
  #     uuid = Uuids::Uuid.create! record: some_record
  #
  #     # Find 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

    attr_readonly  :value
    belongs_to     :record, polymorphic: true
    validate       :record_present?
    before_destroy :forbid_destruction

    # Assigns a #value by default.
    def initialize(*)
      super
      write_attribute :value, SecureRandom.uuid
    end

    private

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

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

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
uuids-1.0.0.pre.rc1 app/models/uuids/uuid.rb
uuids-0.2.0 app/models/uuids/uuid.rb
uuids-0.1.0 app/models/uuids/uuid.rb