Sha256: aa88b32839bd347fc4f2a29a3f1f6507bc48521f59311016d0fcef1a868d0b1d

Contents?: true

Size: 1.15 KB

Versions: 3

Compression:

Stored size: 1.15 KB

Contents

require 'mongoid/ids/collisions'

module Mongoid
  module Ids
    class CollisionResolver
      attr_accessor :create_new_token
      attr_reader :klass
      attr_reader :field_name
      attr_reader :retry_count

      def initialize(klass, field_name, retry_count)
        @create_new_token = Proc.new {|doc|}
        @klass = klass
        @field_name = field_name
        @retry_count = retry_count
        klass.send(:include, Mongoid::Ids::Collisions)
        alias_method_with_collision_resolution(:insert)
        alias_method_with_collision_resolution(:upsert)
      end

      def create_new_token_for(document)
        @create_new_token.call(document)
      end

      private
      def alias_method_with_collision_resolution(method)
        handler = self
        klass.send(:define_method, :"#{method.to_s}_with_#{handler.field_name}_safety") do |method_options = {}|
          self.resolve_token_collisions handler do
            with(:safe => true).send(:"#{method.to_s}_without_#{handler.field_name}_safety", method_options)
          end
        end
        klass.alias_method_chain method.to_sym, :"#{handler.field_name}_safety"
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
mongoid-ids-0.1.8 lib/mongoid/ids/collision_resolver.rb
mongoid-ids-0.1.7 lib/mongoid/ids/collision_resolver.rb
mongoid-ids-0.1.1 lib/mongoid/ids/collision_resolver.rb