Sha256: 9c5daa5002a700c7c5b2acb200f6c13c467eceff699469d9b2bdcfad281690fc

Contents?: true

Size: 1.73 KB

Versions: 2

Compression:

Stored size: 1.73 KB

Contents

require_relative "base/has_uuids"

module Uuids

  # Defines the +has_uuids+ model class helper.
  module Base
    extend ActiveSupport::Concern

    # Methods added to the ActiveRecord model.
    module ClassMethods

      private

      # The helper defines:
      #
      # +uuids+:: the +ActiveRecord+ association with a record's uuids.
      # +uuid+:: a virtual attribute that returns the first value of uuids.
      # <tt>uuid=</tt>:: new uuid setter.
      # <tt>uuids=</tt>:: uuids group setter.
      # <tt>by_uuid</tt>:: the +ActiveRecord+ relation scope.
      #
      # @example
      #   class City < ActiveRecord::Base
      #     has_uuids
      #   end
      #
      #   city = City.create!
      #
      #   city.uuids.map(&:value)
      #   # => 51f50391-fcd2-4f69-aab7-6ef31b29c379
      #
      #   city.uuid
      #   # => 51f50391-fcd2-4f69-aab7-6ef31b29c379
      #
      #   city.uuid = "51f50391-fcd2-4f69-aab7-6ef31b29c379"
      #
      #   city.uuids = [
      #     "51f50391-fcd2-4f69-aab7-6ef31b29c379",
      #     "3ea8fd89-232f-4ed1-90b5-743da173cd7d"
      #   ]
      #
      #   City.by_uuid("51f50391-fcd2-4f69-aab7-6ef31b29c379").to_a == [city]
      #   # => true
      def has_uuids
        has_many :uuids, class_name: "Uuids::Uuid", as: :record, validate: false
        include Uuids::Base::HasUuids
        after_initialize :add_default_uuid
        before_destroy   :prevent_destruction
        validates :uuids, presence: true, on: :update
      end
    end

    private

    # Prevents the module usage outside an ActiveRecord model.
    def self.included(klass)
      unless klass.ancestors.include? ActiveRecord::Base
        fail TypeError.new("#{ klass.name } isn't an ActiveRecord model.")
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
uuids-3.0.0 lib/uuids/base.rb
uuids-2.0.0 lib/uuids/base.rb