Sha256: ae33efcb49447da819dabf465ac697c15c4b1da7fb4d1962fb44973197e52448

Contents?: true

Size: 1.18 KB

Versions: 6

Compression:

Stored size: 1.18 KB

Contents

module Uuidable
  # ActiveRecord mixin
  module ActiveRecord
    extend ActiveSupport::Concern

    class UuidChangeError < RuntimeError; end

    module Finder
      def find(*args)
        if args.first && args.first.is_a?(String) && args.first.match(UUIDTools::UUID_REGEXP)
          find_by_uuid!(*args)
        else
          super
        end
      end
    end

    # ClassMethods
    module ClassMethods
      include Finder

      def uuidable(as_param: true)
        after_initialize { self.uuid = Uuidable.generate_uuid if attributes.keys.include?('uuid') && uuid.blank? }
        validates :uuid, presence: true, uniqueness: true

        if as_param
          define_method :to_param do
            uuid
          end
        end

        define_method :uuid= do |val|
          raise UuidChangeError, 'Uuid changing is bad idea!' unless new_record? || uuid.blank? || uuid == val

          super(val)
        end
      end
    end

    def short_uuid
      UUIDTools::UUID.parse(uuid).hexdigest
    end
  end
end

ActiveSupport.on_load(:active_record) do
  ActiveRecord::Base.send(:include, Uuidable::ActiveRecord)
  ActiveRecord::Relation.send(:prepend, Uuidable::ActiveRecord::Finder)
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
uuidable-0.2.4 lib/uuidable/active_record.rb
uuidable-0.2.3 lib/uuidable/active_record.rb
uuidable-0.2.2 lib/uuidable/active_record.rb
uuidable-0.2.1 lib/uuidable/active_record.rb
uuidable-0.2.0 lib/uuidable/active_record.rb
uuidable-0.1.3 lib/uuidable/active_record.rb