Module: Workarea::Lockable

Included in:
Order
Defined in:
app/models/workarea/lockable.rb

Instance Method Summary collapse

Instance Method Details

#default_lock_valueString

The value set on the lock unless otherwise specified. Derived from the lock_key, the object id of the instance of the Lockable object, and the microseconds since the epoch. A unique key on each instance ensures the instance can unlock itself but cannot be unlocked by any other instance.

Returns:



20
21
22
23
# File 'app/models/workarea/lockable.rb', line 20

def default_lock_value
  @default_lock_value ||=
    "#{lock_key}/#{object_id}/#{DateTime.current.strftime("%Q")}"
end

#lock!(options = {}) ⇒ Boolean

Obtain a lock.

Parameters:

  • options (Hash) (defaults to: {})

    options to pass to lock

Options Hash (options):

  • :value (String)

    The value to set on the lock

Returns:

  • (Boolean)

See Also:

  • for more accepted options.


42
43
44
45
# File 'app/models/workarea/lockable.rb', line 42

def lock!(options = {})
  value = options.delete(:value) || default_lock_value
  Lock.create!(lock_key, value, options)
end

#lock_keyString

The key used to obtain a lock for this object. Requires the object responds to #id. Remains consistent across instances of the same object.

Returns:



8
9
10
# File 'app/models/workarea/lockable.rb', line 8

def lock_key
  "#{self.class.name.underscore}/#{id}/lock"
end

#locked?Boolean

Check if there is a lock for this object.

Returns:

  • (Boolean)


29
30
31
# File 'app/models/workarea/lockable.rb', line 29

def locked?
  Lock.exists?(lock_key)
end

#unlock!(value: nil) ⇒ Boolean

Release the lock. Must match key and value to be released.

Returns:

  • (Boolean)

    true is returned whether or not a matching lock is found. false will only be returned if the deletion of a matched lock fails.



53
54
55
56
# File 'app/models/workarea/lockable.rb', line 53

def unlock!(value: nil)
  value ||= default_lock_value
  Lock.destroy!(lock_key, value)
end