# encoding: utf-8 module Uuids # The module contains ActiveRecord based models. module Models # 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::Models::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 value # The uuid value as defined in RFC4122 # @example The value can be set explicitly # uuid = Uuids::Models::Uuid.new( # value: "d679a46d-13b2-0a78-ad7b-20381441322c" # ) # uuid.value # => "d679a46d-13b2-0a78-ad7b-20381441322c" # @example When not set, the value is assigned by default # uuid = Uuids::Models::Uuid.new # uuid.value # => "51f7314a-90e8-04db-65d6-8a6de83499de" # @return [String] The uuid value. UUID = /\A\h{8}-\h{4}-\h{4}-\h{4}-\h{12}\z/ attr_readonly :value validates :value, format: { with: UUID }, allow_nil: true # @!attribute record # The record the uuid is assigned to. # @return [ActiveRecord::Base] The record the uuid is assigned to. belongs_to :record, polymorphic: true validate :record_present? 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 end