Class: Salesmachine::Api::Worker

Inherits:
Object
  • Object
show all
Includes:
Config, Utils
Defined in:
lib/salesmachine/api/worker.rb

Constant Summary

Constants included from Utils

Utils::UTC_OFFSET_WITHOUT_COLON, Utils::UTC_OFFSET_WITH_COLON

Instance Method Summary collapse

Methods included from Utils

#date_in_iso8601, #datetime_in_iso8601, #formatted_offset, #isoify_dates, #isoify_dates!, #seconds_to_utc_offset, #stringify_keys, #symbolize_keys, #symbolize_keys!, #time_in_iso8601, #uid

Constructor Details

#initialize(queue, api_key, options = {}) ⇒ Worker

public: Creates a new worker

The worker continuously takes messages off the queue and makes requests to the salesmachine.io api

queue - Queue synchronized between client and worker api_key - String of the application’s Api key options - Hash of worker options

batch_size - Fixnum of how many items to send in a batch
on_error   - Proc of what to do on an error


22
23
24
25
26
27
28
29
30
31
# File 'lib/salesmachine/api/worker.rb', line 22

def initialize(queue, api_key, options = {})
  symbolize_keys! options
  @queue = queue
  @api_key = api_key
  @batch_size = options[:batch_size] || Queue::BATCH_SIZE
  @on_error = options[:on_error] || proc { |_status, _error| }
  @batch = []
  @lock = Mutex.new
  @options = options
end

Instance Method Details

#is_requesting?Boolean

public: Check whether we have outstanding requests.

Returns:

  • (Boolean)


54
55
56
# File 'lib/salesmachine/api/worker.rb', line 54

def is_requesting?
  @lock.synchronize { !@batch.empty? }
end

#runObject

public: Continuously runs the loop to check for new events



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/salesmachine/api/worker.rb', line 35

def run
  until Thread.current[:should_exit]
    return if @queue.empty?

    @lock.synchronize do
      until @batch.length >= @batch_size || @queue.empty?
        @batch << @queue.pop
      end
    end
    res = Request.new(@options).post @api_key, @batch

    @lock.synchronize { @batch.clear }

    @on_error.call res.status, res.error unless res.status == 200
  end
end