Class: Mongoid::Orderable::Handlers::Transaction

Inherits:
Object
  • Object
show all
Defined in:
lib/mongoid/orderable/handlers/transaction.rb

Overview

Executes a block within the context of a MongoDB transaction.

Constant Summary collapse

THREAD_KEY =
:__mongoid_orderable_in_txn
RETRY_SLEEP =
0.001

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(doc) ⇒ Transaction

Returns a new instance of Transaction.



13
14
15
# File 'lib/mongoid/orderable/handlers/transaction.rb', line 13

def initialize(doc)
  @doc = doc
end

Instance Attribute Details

#docObject (readonly)

Returns the value of attribute doc.



11
12
13
# File 'lib/mongoid/orderable/handlers/transaction.rb', line 11

def doc
  @doc
end

Instance Method Details

#with_transaction(&block) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/mongoid/orderable/handlers/transaction.rb', line 17

def with_transaction(&block)
  query_cache.uncached do
    if Thread.current[THREAD_KEY]
      yield
    else
      Thread.current[THREAD_KEY] = true
      retries = transaction_max_retries
      begin
        do_transaction(&block)
      rescue Mongo::Error::OperationFailure => e
        sleep(RETRY_SLEEP)
        retries -= 1
        retry if retries >= 0
        raise Mongoid::Orderable::Errors::TransactionFailed.new(e)
      ensure
        Thread.current[THREAD_KEY] = nil
      end
    end
  end
end