Sha256: 31e1bae8f4b0223d4fb02c941bd6ab076add7107d3f065bb16d2a090516a4784

Contents?: true

Size: 824 Bytes

Versions: 1

Compression:

Stored size: 824 Bytes

Contents

class IO

  class Dispatcher

    def initialize
      @io_handlers = [{}, {}, {}]
      @timeout = nil
    end

    def add_io_handler(input: nil, output: nil, exception: nil, handler: nil, &block)
      mode, io = if input
        [0, input]
      elsif output
        [1, output]
      elsif exception
        [2, exception]
      end
      @io_handlers[mode][io] = handler || block
    end

    def set_timeout_handler(timeout, &block)
      @timeout = timeout
      @timeout_handler = block
    end

    def run
      loop do
        if (ready = IO.select(*@io_handlers.map(&:keys), @timeout))
          ready.each_with_index do |mode, i|
            mode.each { |io| @io_handlers[i][io].call(io) }
          end
        else
          @timeout_handler.call if @timeout_handler
        end
      end
    end

  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
io-dispatcher-0.1 lib/io-dispatcher.rb