Class: EventHub

Inherits:
Object
  • Object
show all
Defined in:
lib/event_hub.rb,
lib/event_hub/event.rb,
lib/event_hub/handler.rb,
lib/event_hub/message.rb,
lib/event_hub/version.rb,
lib/event_hub/adapters/test.rb,
lib/event_hub/adapters/test/message.rb

Defined Under Namespace

Modules: Adapters Classes: Event, Handler, IgnoreMessage, IncorrectVersion, Message, NoHandlerDefined, RejectMessage

Constant Summary collapse

VERSION =
'1.1.0'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ EventHub

Returns a new instance of EventHub.



54
55
56
57
58
# File 'lib/event_hub.rb', line 54

def initialize(config)
  @config = config
  @config[:subscribe] ||= {}
  @config[:subscribe].each_value { |subscription| subscription[:handler] = Object.const_get(subscription[:handler]) }
end

Class Method Details

.adapterObject



50
51
52
# File 'lib/event_hub.rb', line 50

def self.adapter
  instance.adapter
end

.configure(config) ⇒ Object



16
17
18
19
20
21
22
23
# File 'lib/event_hub.rb', line 16

def self.configure(config)
  if !config[:on_failure] || !config[:on_failure].respond_to?(:call) || config[:on_failure].arity != 2
    raise ArgumentError, 'EventHub configuration must have `on_failure` callable options with arity == 2'
  end

  @config = config
  @instance = nil
end

.instanceObject



25
26
27
# File 'lib/event_hub.rb', line 25

def self.instance
  @instance ||= new(@config)
end

.publish(event) ⇒ Object



46
47
48
# File 'lib/event_hub.rb', line 46

def self.publish(event)
  instance.adapter.publish(event)
end

.subscribeObject



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/event_hub.rb', line 29

def self.subscribe
  instance.adapter.subscribe do |message|
    handler_class = @config.dig(:subscribe, message.event.to_sym, :handler)
    raise NoHandlerDefined unless handler_class

    handler = handler_class.new(message)
    handler.handle
  rescue IgnoreMessage
    message.ack
  rescue RejectMessage
    message.reject
  rescue Exception => e # rubocop:disable Lint/RescueException
    @config[:on_failure]&.call(e, message)
    message.reject
  end
end

Instance Method Details

#adapterObject



60
61
62
# File 'lib/event_hub.rb', line 60

def adapter
  @adapter ||= Adapters.const_get(@config[:adapter]).new(@config)
end