Sha256: dc1991fb271edf60439f1cd31987eedd9fc58e9f7158a20e8f031f03c5f16671

Contents?: true

Size: 751 Bytes

Versions: 6

Compression:

Stored size: 751 Bytes

Contents

class BackgroundJob
  module Unique
    extend ActiveSupport::Concern

    DEFAULT_TIMEOUT = 10

    included do
      around_perform { |job, block| job.acquire_lock(&block) }
      cattr_accessor :lock_timeout
    end

    def acquire_lock(&block)
      mutex = Redis::Lock.new(
        lock_key(*arguments),
        Shipit.redis,
        expiration: self.class.timeout || DEFAULT_TIMEOUT,
        timeout: self.class.lock_timeout || 0,
      )
      mutex.lock(&block)
    end

    def lock_key(*args)
      ([self.class.name] + args).map { |arg| hash_argument(arg) }.join('-')
    end

    private

    def hash_argument(argument)
      return argument.to_global_id.to_s if argument.respond_to?(:to_global_id)
      argument.to_s
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
shipit-engine-0.2.3 app/jobs/background_job/unique.rb
shipit-engine-0.2.2 app/jobs/background_job/unique.rb
shipit-engine-0.2.1 app/jobs/background_job/unique.rb
shipit-engine-0.2.0 app/jobs/background_job/unique.rb
shipit-engine-0.1.0 app/jobs/background_job/unique.rb
shipit-engine-0.0.1.pre app/jobs/background_job/unique.rb