Sha256: 35dba2c67419c179781d24975ce3589a0cc1f5ee11fbfc08c713659dc9a5232f

Contents?: true

Size: 1.81 KB

Versions: 3

Compression:

Stored size: 1.81 KB

Contents

require "set"

# !!
# Note this code is not currently working in a multi-threaded environment e.g. Puma
# We are migrating to using Renalware.config.broadcast_subscription_map and the Broadcasting
# concern.
#
# Responsible for subscribing listeners to specific classes. This registry
# avoids the issues of global subscriptions which would need to be disabled
# if you wish to use an instance of the class without listeners and avoids
# the issues with Rails auto-loading feature.
#
# This registry is primary used to allow a listener in one module to
# subscribe to broadcasters in a different module allowing the developer to
# manage dependencies in the direction they prefer. Subscriptions within the
# same module should be made directly against the broadcaster, not via
# this registry.
#
# Assumes broadcasters respond to the `subscribe` method.
#
# Usage:
#
# Register the listener class with the broadcaster class.
#
#    SubscriptionRegistry.instance.register(OtherModule::Broadcaster, Listener)
#
# Then in the other module, subscribe listeners registred above to the broadcaster.
#
#    broadcaster = SubscriptionRegistry.instance.subscribe_listeners_to(Broadcaster.new)
#
class SubscriptionRegistry
  include Singleton

  def register(broadcaster_class, listener_class)
    fetch_key(broadcaster_class.name).add(listener_class.name)
  end

  def subscribe_listeners_to(broadcaster_instance)
    broadcaster_instance.tap { subscribe_listeners(broadcaster_instance) }
  end

  private

  def fetch_key(broadcaster_class_name)
    registry[broadcaster_class_name] ||= Set.new
  end

  def subscribe_listeners(broadcaster_instance)
    fetch_key(broadcaster_instance.class.name).each do |listener_class_name|
      broadcaster_instance.subscribe(listener_class_name.constantize.new)
    end
  end

  def registry
    @registry ||= {}
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
renalware-core-2.0.0.pre.beta7 lib/subscription_registry.rb
renalware-core-2.0.0.pre.beta6 lib/subscription_registry.rb
renalware-core-2.0.0.pre.beta5 lib/subscription_registry.rb