Sha256: 3f4beb5adc5a2d8179d2fff91ad7563b7e482c111093731c9986db4a9a84525f

Contents?: true

Size: 1.14 KB

Versions: 10

Compression:

Stored size: 1.14 KB

Contents

# frozen_string_literal: true

module Tobox
  class Worker
    attr_reader :label

    def initialize(label, configuration)
      @label = label
      @wait_for_events_delay = configuration[:wait_for_events_delay]
      @handlers = configuration.handlers || {}
      @fetcher = Fetcher.new(label, configuration)
      @finished = false

      return unless (message_to_arguments = configuration.arguments_handler)

      define_singleton_method(:message_to_arguments, &message_to_arguments)
    end

    def finished?
      @finished
    end

    def finish!
      @finished = true
    end

    def work
      do_work until @finished
    end

    private

    def do_work
      return if @finished

      sum_fetched_events = @fetcher.fetch_events do |event|
        event_type = event[:type].to_sym
        args = message_to_arguments(event)

        if @handlers.key?(event_type)
          @handlers[event_type].each do |handler|
            handler.call(args)
          end
        end
      end

      return if @finished

      sleep(@wait_for_events_delay) if sum_fetched_events.zero?
    end

    def message_to_arguments(event)
      event
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
tobox-0.4.5 lib/tobox/worker.rb
tobox-0.4.4 lib/tobox/worker.rb
tobox-0.4.3 lib/tobox/worker.rb
tobox-0.4.2 lib/tobox/worker.rb
tobox-0.4.1 lib/tobox/worker.rb
tobox-0.4.0 lib/tobox/worker.rb
tobox-0.3.2 lib/tobox/worker.rb
tobox-0.3.1 lib/tobox/worker.rb
tobox-0.3.0 lib/tobox/worker.rb
tobox-0.2.0 lib/tobox/worker.rb