Class: Clamour::Registry

Inherits:
Object
  • Object
show all
Defined in:
lib/clamour/registry.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Registry

Returns a new instance of Registry.



12
13
14
15
16
# File 'lib/clamour/registry.rb', line 12

def initialize(&block)
  @handlers = Hash.new { |mapping, type| mapping[type] = Set.new }
  @message_classes = Hash.new
  change(&block) if block_given?
end

Instance Attribute Details

#handlersHash<Set<Class>> (readonly)

Returns store handler classes.

Returns:

  • (Hash<Set<Class>>)

    store handler classes



7
8
9
# File 'lib/clamour/registry.rb', line 7

def handlers
  @handlers
end

#message_classesHash (readonly)

Returns:

  • (Hash)


10
11
12
# File 'lib/clamour/registry.rb', line 10

def message_classes
  @message_classes
end

Instance Method Details

#change(&block) ⇒ Object



31
32
33
34
# File 'lib/clamour/registry.rb', line 31

def change(&block)
  instance_eval(&block)
  self
end

#on(mappings = {}) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/clamour/registry.rb', line 36

def on(mappings = {})
  mappings.each do |message_class, handlers_list|
    raise ArgumentError.new("#{message_class} must include Clamour::Message") unless message_class < Clamour::Message
    Array.wrap(handlers_list).flatten.compact.each do |handler|
      raise ArgumentError.new("Handler #{handler} must be a class") unless handler.is_a?(Class)
      message_type = message_class.type
      message_classes[message_type] = message_class
      handlers[message_type].add(handler)
    end
  end
end

#route(type, &block) ⇒ Object

Raises:

  • (ArgumentError)


18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/clamour/registry.rb', line 18

def route(type, &block)
  raise ArgumentError.new('Something has to be routed') if type.blank?
  message_class = message_classes[type]
  found_handlers = handlers[type]
  if message_class.present? && found_handlers.present?
    found_handlers.each do |handler|
      block.call(handler, message_class)
    end
  else
    puts "Could not find message class or handler for #{type}"
  end
end