Sha256: 537e16d8b13121588aeb585939834c9d9611921f36cc6eed5bf3635100bf5ff7

Contents?: true

Size: 1.57 KB

Versions: 1

Compression:

Stored size: 1.57 KB

Contents

# frozen_string_literal: true

require 'active_support/concern'

module WithAdvisoryLock
  module Concern
    extend ActiveSupport::Concern
    delegate :with_advisory_lock, :with_advisory_lock!, :advisory_lock_exists?, to: 'self.class'

    class_methods do
      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)
        result = with_advisory_lock_result(lock_name, options, &block)
        unless result.lock_was_acquired?
          raise WithAdvisoryLock::FailedToAcquireLock, lock_name
        end

        result.result
      end

      def with_advisory_lock_result(lock_name, options = {}, &block)
        impl = impl_class.new(connection, lock_name, options)
        impl.with_advisory_lock_if_needed(&block)
      end

      def advisory_lock_exists?(lock_name)
        impl = impl_class.new(connection, lock_name, 0)
        impl.already_locked? || !impl.yield_with_lock.lock_was_acquired?
      end

      def current_advisory_lock
        lock_stack_key = WithAdvisoryLock::Base.lock_stack.first
        lock_stack_key && lock_stack_key[0]
      end

      private

      def impl_class
        adapter = WithAdvisoryLock::DatabaseAdapterSupport.new(connection)
        if adapter.postgresql?
          WithAdvisoryLock::PostgreSQL
        elsif adapter.mysql?
          WithAdvisoryLock::MySQL
        else
          WithAdvisoryLock::Flock
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
with_advisory_lock-5.0.0 lib/with_advisory_lock/concern.rb