Sha256: 74beefca6444d972c2cb6b9bc539bba23a3d62ce9a260d5121cd0df7c83d8270

Contents?: true

Size: 1.79 KB

Versions: 15

Compression:

Stored size: 1.79 KB

Contents

# encoding: utf-8

module Punchblock
  class Client
    extend ActiveSupport::Autoload

    autoload :ComponentRegistry

    include HasGuardedHandlers

    attr_reader :connection, :event_queue, :component_registry

    delegate :run, :stop, :to => :connection

    # @param [Hash] options
    # @option options [Connection::XMPP] :connection The Punchblock connection to use for this session
    #
    def initialize(options = {})
      @event_queue = Queue.new
      @connection = options[:connection]
      @connection.event_handler = lambda { |event| self.handle_event event } if @connection
      register_initial_handlers
      @component_registry = ComponentRegistry.new
      @write_timeout = options[:write_timeout] || 3
    end

    def handle_event(event)
      event.client = self
      if event.source
        event.source.add_event event
      else
        trigger_handler :event, event
      end
    end

    def register_event_handler(*guards, &block)
      register_handler :event, *guards, &block
    end

    def register_initial_handlers
      register_handler_with_priority :event, -10 do |event|
        event_queue.push event
      end
    end

    def register_component(component)
      component_registry << component
    end

    def find_component_by_id(component_id)
      component_registry.find_by_id component_id
    end

    def execute_command(command, options = {})
      async = options.has_key?(:async) ? options.delete(:async) : true
      command.client = self
      if command.respond_to?(:register_handler)
        command.register_handler :internal do |event|
          trigger_handler :event, event
        end
      end
      connection.write command, options
      command.response(@write_timeout).tap { |result| raise result if result.is_a? Exception } unless async
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
punchblock-1.6.1 lib/punchblock/client.rb
punchblock-1.6.0 lib/punchblock/client.rb
punchblock-1.5.3 lib/punchblock/client.rb
punchblock-1.5.2 lib/punchblock/client.rb
punchblock-1.5.1 lib/punchblock/client.rb
punchblock-1.5.0 lib/punchblock/client.rb
punchblock-1.4.1 lib/punchblock/client.rb
punchblock-1.4.0 lib/punchblock/client.rb
punchblock-1.3.0 lib/punchblock/client.rb
punchblock-1.2.0 lib/punchblock/client.rb
punchblock-1.1.0 lib/punchblock/client.rb
punchblock-1.0.0 lib/punchblock/client.rb
punchblock-0.12.0 lib/punchblock/client.rb
punchblock-0.11.0 lib/punchblock/client.rb
punchblock-0.10.0 lib/punchblock/client.rb