with_advisory_lock
with_advisory_lock copied to clipboard
Why not raise exception when the lock couldn't be acquired in the given timeout?
I know that this is documented behaviour but it trips me over every time when i use this gem. I think it would be more sensible to raise an error if it couldn't acquire the lock, instead of simply not executing the block. The caller could handle the exception if executing the block was optional.
Fair point. You wanna take a it ?
Needed something similar, wrote a wrapper over theadvisory_lock
to achieve to this
module AdvisoryLockManager
class LockAcquireError < StandardError; end
def self.with_lock!(lock_id, opts, &block)
raise LockAcquireError.new("Failed to acquire error for #{lock_id}") unless with_lock(lock_id, opts, &block)
end
def self.with_lock(lock_id, opts = {}, &block)
ActiveRecord::Base.with_advisory_lock(lock_id, opts) do
yield
end
end
end
Use it like this
AdvisoryLockManager.with_lock!("hachi",{timeout_seconds: 1}) { sleep 10 }
Patch should ideally look like this at https://github.com/ClosureTree/with_advisory_lock/blob/master/lib/with_advisory_lock/concern.rb
module ClassMethods
def with_advisory_lock(lock_name, options = {}, &block)
result = with_advisory_lock_result(lock_name, options, &block)
result.lock_was_acquired? ? result.result : false
end
def with_advisory_lock!(lock_name, options = {}, &block)
raise WithAdvisoryLock::LockAcquireError.new("Failed to acquire lock for #{lock_name}" unless with_advisory_lock(lock_name,options,&block)
end
......
end
I can submit a patch to the library if it is needed @seuros ?
yes
@seuros This should be good right ?
#65