File: object.rb

package info (click to toggle)
ruby-wisper 3.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 276 kB
  • sloc: ruby: 1,231; makefile: 4
file content (43 lines) | stat: -rw-r--r-- 1,310 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
41
42
43
# @api private

module Wisper
  class ObjectRegistration < Registration
    attr_reader :with, :prefix, :allowed_classes, :broadcaster

    def initialize(listener, **options)
      super(listener, **options)
      @with   = options[:with]
      @prefix = ValueObjects::Prefix.new options[:prefix]
      @allowed_classes = Array(options[:scope]).map(&:to_s).to_set
      @broadcaster = map_broadcaster(options[:async] || options[:broadcaster])
    end

    def broadcast(event, publisher, *args, **kwargs)
      method_to_call = map_event_to_method(event)
      if should_broadcast?(event) && listener.respond_to?(method_to_call) && publisher_in_scope?(publisher)
        broadcaster.broadcast(listener, publisher, method_to_call, *args, **kwargs)
      end
    end

    private

    def publisher_in_scope?(publisher)
      allowed_classes.empty? || publisher.class.ancestors.any? { |ancestor| allowed_classes.include?(ancestor.to_s) }
    end

    def map_event_to_method(event)
      prefix + (with || event).to_s
    end

    def map_broadcaster(value)
      return value if value.respond_to?(:broadcast)
      value = :async   if value == true
      value = :default if value == nil
      configuration.broadcasters.fetch(value)
    end

    def configuration
      Wisper.configuration
    end
  end
end