Skip to content

Commit

Permalink
Reinforce logical linings of a Lock
Browse files Browse the repository at this point in the history
  • Loading branch information
northeastprince committed Jan 21, 2025
1 parent 6130f4e commit 2c95d29
Showing 1 changed file with 12 additions and 9 deletions.
21 changes: 12 additions & 9 deletions app/models/lock.rb
Original file line number Diff line number Diff line change
@@ -1,37 +1,40 @@
class Lock < ApplicationRecord
scope :expired, -> { where "expiration <= ?", Time.now }
scope :active, -> { expired.invert_where }

class << self
def acquire(key, limit: 1, duration: nil, &block)
def acquire(key, limit: 1, duration: nil)
lock = nil
transaction do
lock = find_by(key:) || create!(key:, expiration: duration&.from_now)
if lock.capacity == limit
lock = active.find_by(key:) || create!(key:, expiration: duration&.from_now)

if lock.capacity >= limit
return false
else
lock.acquire
end
end

lock.acquire

begin
yield block
yield
true
ensure
lock.release
end
end
end

def acquire(capacity = 1)
increment!(:capacity, capacity)
increment! :capacity, capacity
end

def release(quantity = 1)
transaction do
reload
if capacity == 1
if capacity <= 1
destroy!
else
decrement!(:capacity, quantity)
decrement! :capacity, quantity
end
end
end
Expand Down

0 comments on commit 2c95d29

Please sign in to comment.