Sha256: d2d8d0f8875ca1114315d633bcdcd043db5bfbdefa093ada8720799ccbc6bb6b

Contents?: true

Size: 1.79 KB

Versions: 1

Compression:

Stored size: 1.79 KB

Contents

module Uuids

  # Creates required `#uuids` attribute of the ActiveRecord model.
  module Base
    extend ActiveSupport::Concern

    # Prevents the module usage outside an ActiveRecord model.
    #
    #   class Text < String
    #     include Uuids::Base
    #   end
    #   # => raises a TypeError
    #
    def self.included(klass)
      unless klass.ancestors.include? ActiveRecord::Base
        fail TypeError.new("#{ klass.name } isn't an ActiveRecord model.")
      end
    end

    # Methods added to the ActiveRecord model.
    module ClassMethods

      private

      # Declares:
      #
      # * +uuids+ association attribute;
      # * +uuid+ method (string);
      # * <tt>uuid</tt> relation scope.
      #
      def has_uuids
        define_uuids
        define_uuid_getter
        define_scope
      end

      # Defines the +uuids+ association attribute;
      def define_uuids
        has_many :uuids, class_name: "Uuids::Uuid", as: :record, validate: false
        before_create  :add_default_uuid
        before_destroy :prevent_destruction
        validates :uuids, presence: true, on: :update
      end

      # Defines the +uuid+ method
      def define_uuid_getter
        class_eval "def uuid; uuids.first.try(:value); end"
      end

      # Defines the <tt>uuid</tt> relation scope.
      def define_scope
        scope :by_uuid, ->(value) {
          joins(:uuids).where(uuids_uuids: { value: value }).uniq
        }
      end
    end

    private

    # Creates the uuids by default preventing a record from being ureferrable
    def add_default_uuid
      uuids.present? || uuids.new
    end

    # Prevents destruction of a record before its uuids assigned to another one
    def prevent_destruction
      return true if uuids.blank?
      errors.add :base, :uuids_present
      false
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
uuids-1.0.0.pre.rc1 lib/uuids/base.rb