Sha256: 95447a7c82a59c482b9d479f6a23614829b938c64c5244b6a725fb572c39b1ce

Contents?: true

Size: 1.88 KB

Versions: 4

Compression:

Stored size: 1.88 KB

Contents

# frozen_string_literal: true
module Steam
  module Handler
    # Defines the base Handler
    #
    # @example Creating a handler
    #   class MyHandler
    #     include HandlerBase
    #
    #     handles :CLIENT_LOG_OFF
    #
    #     def handle(packet)
    #     end
    #   end
    module Base
      # Inject class methods into the hosting class
      def self.included(base)
        base.send(:extend, ClassMethods)
      end

      # The Client object
      #
      # @see Client
      attr_reader :client

      # Instantiate a Handler with a Client
      #
      # @example Creating a Handler
      #   class MyHandler
      #     include Handler::Base
      #   end
      #
      #   handler = MyHandler.new(Client.new)
      def initialize(client)
        @client = client
      end

      # Handle the incoming packet
      #
      # @param _packet [Networking::Packet] the packet to handle
      def handle(_packet)
        raise NotImplementedError
      end

      # Determines if this handler can handle the given message type. It
      # compares the symbols given via .handles to known EMsg constants.
      #
      # @param msg [Integer]
      # @return [Bool]
      def handles?(msg)
        self.class.handled_messages.any? { |m| msg == m }
      end

      # Send a message to the client
      #
      # @param msg [Message] The Message to send to steam
      # @return [Bool]
      def send_msg(msg)
        @client.send_msg(msg)
      end

      # Inject methods into the hosting class
      module ClassMethods
        # The list of EMsgs that this handler knows
        # how to handle
        def handled_messages
          @handled_messages ||= []
        end

        # Specify with EMsgs this Handler cares about
        def handles(*args)
          handled_messages << args.dup.flatten
          handled_messages.flatten!
          handled_messages.uniq!
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

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