Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
j_api_agent / lib / j_api_agent / agent.rb
Size: Mime:
require "rest_client"
require "json"
require "resque"

module JApiAgent
	module Agent
		module ClassMethods

			def job_queue(queue)
				@queue = queue
			end

			def bulk_limit(limit)
				@bulk_limit = limit
			end

      def batch(type,param_name,params,other_params = {})
      	result = []
				params.each_slice(@bulk_limit).each do |param|
					param_string = param.join(',')
					bulk_params = other_params.merge({param_name => param_string})
					result += execute(type, bulk_params)
        end
        result
      end

			def after_delayed(&after_block)
				@after_delayed_block = after_block
			end

      def before_delayed(&before_block)
        @before_delayed_block = before_block
      end

			def api_call(&block)
				@api_call_block = block
			end

			def execute(type, *params)
				case type
				when :realtime
          @before_delayed_block.call(*params) unless @before_delayed_block.nil?
					return @api_call_block.call(*params)
				when :delayed
					Resque.enqueue(self, *params)
				else
					raise ArgumentError, "execution type should be either realtime or delayed"
				end
			end

			def perform(*params)
        @before_delayed_block.call(*params) unless @before_delayed_block.nil?
        resp = @api_call_block.call(*params)
        @after_delayed_block.call(resp)
     end
		end

		def self.included(receiver)
			receiver.extend         ClassMethods
			receiver.bulk_limit 1

			receiver.instance_eval { @after_delayed_block = Proc.new{} }
			receiver.instance_eval { @api_call_block = Proc.new{} }
			receiver.instance_eval { @before_delayed_block = Proc.new{} }
    end
	end
end