Module: Mongoid::Locking::Retry::ClassMethods

Defined in:
lib/mongoid/locking/retry.rb

Overview

:nodoc:

Since:

  • 0.1.0

Instance Method Summary collapse

Instance Method Details

#backoff_algorithm(retries) ⇒ Object

Since:

  • 0.1.0



61
62
63
# File 'lib/mongoid/locking/retry.rb', line 61

def backoff_algorithm(retries)
  (2 + rand)**retries
end

#with_locking(max_retries: 3) ⇒ Object

Retries the block of code a specified number of times when a Mongoid::StaleObjectError is raised.

Examples:

Person.with_locking do
  person = Person.find(existing.id)
  Person.update!(name: "Person 1 updated")
end

Parameters:

  • max_retries (Integer) (defaults to: 3)

    The maximum number of times to retry

Returns:

  • (Object)

    The result of the block

Since:

  • 0.1.0



47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/mongoid/locking/retry.rb', line 47

def with_locking(max_retries: 3)
  retries = 0

  begin
    yield
  rescue Mongoid::StaleObjectError
    retries += 1
    raise if retries > max_retries

    sleep Mongoid::Locking.backoff_algorithm(retries)
    retry
  end
end