Sha256: d31739ff624540b48e9722ac0e045d8a766a3a9aa56c097a3549379901e972d7

Contents?: true

Size: 1.48 KB

Versions: 6

Compression:

Stored size: 1.48 KB

Contents

require 'active_support/concern'
require 'global_id'

begin
  require 'sidekiq'
  require 'sidekiq/api'
rescue LoadError
  raise Services::BackgroundProcessorNotFound
end

module Services
  module Asyncable
    extend ActiveSupport::Concern

    ASYNC_METHOD_SUFFIXES = %i(async in at).freeze

    included do
      include Sidekiq::Worker
    end

    module ClassMethods
      ASYNC_METHOD_SUFFIXES.each do |async_method_suffix|
        define_method "call_#{async_method_suffix}" do |*args|
          args = args.map do |arg|
            arg.respond_to?(:to_global_id) ? arg.to_global_id : arg
          end
          self.public_send "perform_#{async_method_suffix}", *args
        end
      end
    end

    def perform(*args)
      args = args.map do |arg|
        GlobalID::Locator.locate(arg) || arg
      end
      # If the `call` method takes any kwargs and the last argument is a hash, symbolize the hash keys,
      # otherwise they won't be recognized as kwards when splatted.
      # Since the arguments to `perform` are serialized to the database before Sidekiq picks them up,
      # symbol keys are converted to strings.
      call_method = method(:call)
      # Find the first class that inherits from `Services::Base`.
      while !(call_method.owner < Services::Base)
        call_method = call_method.super_method
      end
      if call_method.parameters.map(&:first).grep(/\Akey/).any? && args.last.is_a?(Hash)
        args.last.symbolize_keys!
      end
      call *args
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
services-7.2.1 lib/services/asyncable.rb
services-7.2.0 lib/services/asyncable.rb
services-7.1.2 lib/services/asyncable.rb
services-7.1.1 lib/services/asyncable.rb
services-7.1.0 lib/services/asyncable.rb
services-7.0.3 lib/services/asyncable.rb