Sha256: af470da363d1ac4dbccd4752c73d3cee096417f5ed3d72acaf7b532b61d785e8

Contents?: true

Size: 824 Bytes

Versions: 2

Compression:

Stored size: 824 Bytes

Contents

module Keepit
  module Locker
    GLOBAL = "global".freeze
    KEY = "keepit:locks".freeze
    EXPIRES_IN = 60

    def self.lock(resources, blocking = false)
      result = ::Keepit.redis.sadd(KEY, resources)
      sleep(EXPIRES_IN) if blocking

      result
    end

    def self.unlock(resources, blocking = false)
      result = ::Keepit.redis.srem(KEY, resources)
      sleep(EXPIRES_IN) if blocking

      result
    end

    def self.locked?(resource, check_global: true)
      if check_global
        locked_resources.any? { |r| r == resource || r == GLOBAL }
      else
        locked_resources.any? { |r| r == resource }
      end
    end

    def self.locked_resources
      ::Keepit::TransientStore.fetch(:locks, expires_in: EXPIRES_IN) do
        Array(::Keepit.redis.smembers(KEY))
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
keepit-0.1.1 lib/keepit/locker.rb
keepit-0.1.0 lib/keepit/locker.rb