Sha256: 554d9f3e8bf9f9489cc73c759df2b796e2d14d5b4cf06ef9b3d414db199f13c4

Contents?: true

Size: 1.54 KB

Versions: 3

Compression:

Stored size: 1.54 KB

Contents

# frozen_string_literal: true
module Steam
  module Handler
    # Holds a collection of Handler objects
    #
    # @example Create a collection of Handler objects
    #   collection = Handler::Collection.new
    #   collection << MyHandler.new(client)
    class Collection
      include Enumerable

      # Creates an empty list of handlers
      def initialize
        @handlers = []
      end

      # Handle a packet. If a handler is found that cares about this packet,
      # the packet object is passed to the handler.
      #
      # @param packet [Networking::Packet] the packet to handle
      def handle(packet)
        handler = find_handler(packet.msg_type)

        if handler.nil?
          emsg = EMsgUtil.new(packet.emsg)
          Steam.logger.debug("No hander found for: #{emsg.name}")
          return false
        end

        handler.handle(packet)
      end

      # Add a handler to the collection
      #
      # @param handlers [Array<Handler::Base>] the handler to add
      def add(*handlers)
        handlers.each do |handler|
          @handlers << handler
          Steam.logger.debug("Added handler #{handler.class.name}")
        end
      end

      # Iterate through each Handler. Allows the collection to act as an
      # Enumerable
      def each(&block)
        @handlers.each(&block)
      end

      private

      # @api private
      # :nocov:
      def find_handler(msg)
        message_handlers = @handlers.select do |handler|
          handler.handles?(msg)
        end
        message_handlers.first
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
steamrb-0.1.3 lib/steam/handler/collection.rb
steamrb-0.1.2 lib/steam/handler/collection.rb
steamrb-0.1.1 lib/steam/handler/collection.rb