Module: ZeevexReliability::OptimisticLockRetryable::InstanceMethods

Defined in:
lib/zeevex_reliability/optimistic_lock_retryable.rb

Instance Method Summary collapse

Instance Method Details

#with_optimistic_retry(options = {}, &block) ⇒ Object

Options:

  • :tries - Number of retries to perform. Defaults to 3.

If the final attempts also receives an exception, that exception will be raised.

Example

model.with_optimistic_retry(:tries => 5) do
  # your model frobbing code here
  model.save!
end


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/zeevex_reliability/optimistic_lock_retryable.rb', line 37

def with_optimistic_retry(options = {}, &block)
  opts = { :tries => 3 }.merge(options)
  retries = opts[:tries]

  # a retry may reload the object, so log a message that this
  # may be used incorrectly
  if changed?
    logger.warn "WARNING: with_optimistic_retry called on changed object; if the save fails, changes will be lost!"
  end

  begin
    return yield
  rescue ActiveRecord::StaleObjectError
    if (retries -= 1) > 0
      self.reload
      retry
    else
      raise
    end
  end
end