Sha256: 046afe48a4042c3f2a950515536d1de4893e26acb815abff4eb77a6b2e6dc851

Contents?: true

Size: 1.46 KB

Versions: 1

Compression:

Stored size: 1.46 KB

Contents

module Mongoid
  module Locker
    # Normalizes queries between Mongoid 2 and 3.
    module Wrapper
      IS_OLD_MONGOID = Mongoid::VERSION.start_with? '2'

      # Update the document for the provided Class matching the provided query with the provided setter.
      #
      # @param [Class] The model class
      # @param [Hash] The Mongoid query
      # @param [Hash] The Mongoid setter
      # @return [Boolean] true if the document was successfully updated, false otherwise
      def self.update klass, query, setter
        if IS_OLD_MONGOID
          error_obj = klass.collection.update(query, setter, :safe => true)
          error_obj['n'] == 1
        else
          !!klass.where(query).find_and_modify(setter, :new => false)
        end
      end

      # Determine whether the provided document is locked in the database or not.
      #
      # @param [Class] The model instance
      # @return [Time] The timestamp of when the document is locked until, nil if not locked.
      def self.locked_until doc
        existing_query = {
          :_id => doc.id,
          :locked_until => {'$exists' => true}
        }

        if IS_OLD_MONGOID
          existing = doc.class.collection.find_one(existing_query, :fields => {:locked_until => 1})
          existing ? existing['locked_until'] : nil
        else
          existing = doc.class.where(existing_query).limit(1).only(:locked_until).first
          existing ? existing.locked_until : nil
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mongoid-locker-0.2.0 lib/mongoid/locker/wrapper.rb