Class: EventTrain::Channel

Inherits:
Object
  • Object
show all
Defined in:
lib/event_train/channel.rb

Overview

A channel where events may be published and to which consumers may subscribe.

Interacting with a channel directly is not mandatory, you may use the global EventTrain module to access it without the channel instance. The top-level module acts as a singleton.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name:, logger: default_logger) ⇒ Channel

Returns a new instance of Channel.



15
16
17
18
19
# File 'lib/event_train/channel.rb', line 15

def initialize(name:, logger: default_logger)
  @name = name
  @logger = logger
  @subscribed_blocks = []
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger.



13
14
15
# File 'lib/event_train/channel.rb', line 13

def logger
  @logger
end

#nameObject (readonly)

Returns the value of attribute name.



13
14
15
# File 'lib/event_train/channel.rb', line 13

def name
  @name
end

Instance Method Details

#publish(event_name:, event_data:) ⇒ Object

Raises:

  • (ArgumentError)


21
22
23
24
25
26
# File 'lib/event_train/channel.rb', line 21

def publish(event_name:, event_data:)
  raise ArgumentError, "event_name must be a Symbol" unless event_name.is_a?(Symbol)
  subscribed_blocks.map do |block|
    block.call(event_name: event_name, event_data: event_data)
  end
end

#subscribe(&block) ⇒ Object



28
29
30
31
32
33
# File 'lib/event_train/channel.rb', line 28

def subscribe(&block)
  unless block_given?
    raise ArgumentError, "A block must be passed to subscribe"
  end
  add_subscribed_block(&block)
end