Sha256: 1ee44ea9a0b0d3f8d7e801888df593c4c7ead121c896bf51773066e040e88ce1

Contents?: true

Size: 1.47 KB

Versions: 1

Compression:

Stored size: 1.47 KB

Contents

# encoding: UTF-8

require 'active_support/dependencies'

module JobDispatch
  class Worker

    #
    # This represents a unit of work to be done. It will be serialised to Mongo database
    #
    class Item
      attr_accessor :job_id
      attr :target
      attr :method
      attr :params
      attr :result
      attr :status

      def initialize(target, method, *params)
        @target, @method, @params = target, method, params
      end

      # execute the method on the target with the given parameters
      # This will capture standard exceptions for return over network.
      def execute
        begin
          JobDispatch.logger.info "Worker executing job #{job_id}: #{target}.#{method}"
          Thread.current["JobDispatch::Worker.job_id"] = job_id
          @klass = target.constantize
          @result = @klass.__send__(method.to_sym, *params)
          @status = :success
        rescue StandardError => ex

          notify_error(ex) rescue nil

          @result = {
              class: ex.class.to_s,
              message: ex.to_s,
              backtrace: ex.backtrace,
          }
          @status = :error
          JobDispatch.logger.debug ex
        ensure
          Thread.current["JobDispatch::Worker.job_id"] = nil
          JobDispatch.logger.info "Worker completed job #{job_id}: #{target}.#{method}, status: #{@status}"
        end
      end

      def notify_error(exception)
        # subclass this to send error notifications
      end
    end
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
job_dispatch-0.2.0 lib/job_dispatch/worker/item.rb