module Downstream

Constants

VERSION

Public Class Methods

config() click to toggle source
# File lib/downstream.rb, line 18
def config
  @config ||= Config.new
end
configure() { |config| ... } click to toggle source
# File lib/downstream.rb, line 22
def configure
  yield config
end
publish(event) click to toggle source
# File lib/downstream.rb, line 44
def publish(event)
  pubsub.publish("#{config.namespace}.#{event.type}", event)
end
subscribe(subscriber = nil, to: nil, async: false, &block) click to toggle source
# File lib/downstream.rb, line 26
def subscribe(subscriber = nil, to: nil, async: false, &block)
  subscriber ||= block if block
  raise ArgumentError, "Subsriber must be present" if subscriber.nil?

  identifier = construct_identifier(subscriber, to)

  pubsub.subscribe(identifier, subscriber, async: async)
end
subscribed(subscriber, to: nil, &block) click to toggle source

temporary subscriptions

# File lib/downstream.rb, line 36
def subscribed(subscriber, to: nil, &block)
  raise ArgumentError, "Subsriber must be present" if subscriber.nil?

  identifier = construct_identifier(subscriber, to)

  pubsub.subscribed(identifier, subscriber, &block)
end

Private Class Methods

construct_identifier(subscriber, to) click to toggle source
# File lib/downstream.rb, line 50
def construct_identifier(subscriber, to)
  to ||= infer_event_from_subscriber(subscriber) if subscriber.is_a?(Module)

  if to.nil?
    raise ArgumentError, "Couldn't infer event from subscriber. " \
                          "Please, specify event using `to:` option"
  end

  identifier = if to.is_a?(Class) && Event >= to
    to.identifier
  else
    to
  end

  "#{config.namespace}.#{identifier}"
end
infer_event_from_subscriber(subscriber) click to toggle source
# File lib/downstream.rb, line 67
def infer_event_from_subscriber(subscriber)
  event_class_name = subscriber.name.split("::").yield_self do |parts|
    # handle explicti top-level name, e.g. ::Some::Event
    parts.shift if parts.first.empty?
    # drop last part – it's a unique subscriber name
    parts.pop

    parts.last.sub!(/^On/, "")

    parts.join("::")
  end

  event_class_name.safe_constantize
end