Class: Spree::OrderMutex

Inherits:
Base
  • Object
show all
Defined in:
app/models/spree/order_mutex.rb

Defined Under Namespace

Classes: LockFailed

Class Method Summary (collapse)

Methods inherited from Base

display_includes, #initialize_preference_defaults, page, preference

Methods included from Preferences::Preferable

#default_preferences, #defined_preferences, #get_preference, #has_preference!, #has_preference?, #preference_default, #preference_type, #set_preference

Class Method Details

+ (Object) with_lock!(order)

Obtain a lock on an order, execute the supplied block and then release the lock. Raise a LockFailed exception immediately if we cannot obtain the lock. We raise instead of blocking to avoid tying up multiple server processes waiting for the lock.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'app/models/spree/order_mutex.rb', line 13

def with_lock!(order)
  raise ArgumentError, "order must be supplied" if order.nil?

  # limit the maximum lock time just in case a lock is somehow left in place accidentally
  expired.where(order: order).delete_all

  begin
    order_mutex = create!(order: order)
  rescue ActiveRecord::RecordNotUnique
    error = LockFailed.new("Could not obtain lock on order #{order.id}")
    logger.error error.inspect
    raise error
  end

  yield

ensure
  order_mutex.destroy if order_mutex
end