File: emitter.rb

package info (click to toggle)
ruby-http-2 1.1.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 13,360 kB
  • sloc: ruby: 6,031; makefile: 4
file content (40 lines) | stat: -rw-r--r-- 1,086 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# frozen_string_literal: true

module HTTP2
  # Basic event emitter implementation with support for persistent and
  # one-time event callbacks.
  #
  module Emitter
    # Subscribe to all future events for specified type.
    #
    # @param event [Symbol]
    # @param block [Proc] callback function
    def on(event, &block)
      raise ArgumentError, "must provide callback" unless block

      @listeners[event] << block
    end

    # Subscribe to next event (at most once) for specified type.
    #
    # @param event [Symbol]
    # @param block [Proc] callback function
    def once(event, &block)
      on(event) do |*args, &callback|
        block.call(*args, &callback)
        :delete
      end
    end

    # Emit event with provided arguments.
    #
    # @param event [Symbol]
    # @param args [Array] arguments to be passed to the callbacks
    # @param block [Proc] callback function
    def emit(event, *args, &block)
      @listeners[event].delete_if do |cb|
        :delete == cb.call(*args, &block) # rubocop:disable Style/YodaCondition
      end
    end
  end
end