Sha256: d834e21d6017edb19cb8f6968ca81d4c3289977e07a54b90e1963b841792310b

Contents?: true

Size: 1.97 KB

Versions: 1

Compression:

Stored size: 1.97 KB

Contents

require 'sidekiq'

module Softwear
  module Lib
    module Enqueue
      extend ActiveSupport::Concern

      class Worker
        include ::Sidekiq::Worker

        def perform(model_name, id, method, *args)
          model_name.constantize.find(id).send(method, *args)
        end
      end

      module ClassMethods
        def enqueue(*method_names)
          if method_names.last.is_a?(Hash)
            options = method_names.pop
          else
            options = {}
          end
          raise "enqueue what?" if method_names.empty?

          method_names.each do |method_name|
            class_eval <<-RUBY, __FILE__, __LINE__ + 1
              def self.#{method_name}(id, *args)
                find(id).#{method_name}(*args)
              end
            RUBY

            if Rails.env.production?
              class_eval <<-RUBY, __FILE__, __LINE__ + 1
                def self.enqueue_#{method_name}(id, *args)
                  ::Sidekiq::Client.push(
                    'class' => ::Softwear::Lib::Enqueue::Worker,
                    'args'  => [name, id, #{method_name.inspect}] + args,
                    'queue' => #{options[:queue]}
                  )
                end

                def enqueue_#{method_name}(*args)
                  self.class.enqueue_#{method_name}(*args)
                end
              RUBY
            else
              class_eval <<-RUBY, __FILE__, __LINE__ + 1
                def self.enqueue_#{method_name}(id, *args)
                  self.#{method_name}(id, *args)
                end

                def enqueue_#{method_name}(*args)
                  self.#{method_name}(*args)
                end
              RUBY
            end
          end

          r = method_names.map { |m| "enqueue_#{m}".to_sym }
          r.size == 1 ? r.first : r
        end
      end

      included do
        extend ClassMethods

        def enqueue(method_name, *args)
          send("enqueue_#{method_name}", *args)
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
softwear-lib-1.8.2 lib/softwear/lib/enqueue.rb