class RemoteLock
Constants
- DEFAULT_OPTIONS
- VERSION
Public Class Methods
new(adapter, prefix = nil)
click to toggle source
# File lib/remote_lock.rb, line 10 def initialize(adapter, prefix = nil) raise "Invalid Adapter" unless Adapters::Base.valid?(adapter) @adapter = adapter @prefix = prefix end
Public Instance Methods
acquire_lock(key, options = {})
click to toggle source
# File lib/remote_lock.rb, line 29 def acquire_lock(key, options = {}) options = DEFAULT_OPTIONS.merge(options) 1.upto(options[:retries]) do |attempt| success = @adapter.store(key_for(key), options[:expiry]) return if success break if attempt == options[:retries] Kernel.sleep(2 ** (attempt + rand - 1) * options[:initial_wait]) end raise RemoteLock::Error, "Couldn't acquire lock for: #{key}" end
acquired?(key)
click to toggle source
# File lib/remote_lock.rb, line 44 def acquired?(key) @adapter.has_key?(key_for(key)) end
release_lock(key)
click to toggle source
# File lib/remote_lock.rb, line 40 def release_lock(key) @adapter.delete(key_for(key)) end
synchronize(key, options={}) { || ... }
click to toggle source
# File lib/remote_lock.rb, line 16 def synchronize(key, options={}) if acquired?(key) yield else acquire_lock(key, options) begin yield ensure release_lock(key) end end end
Private Instance Methods
key_for(string)
click to toggle source
# File lib/remote_lock.rb, line 50 def key_for(string) [@prefix, "lock", string].compact.join('|') end