Sha256: e8bfcb32c9c0faeeec5f207de7f8b088e37e71f7cf3c5f0d9f1c8cf032c221c4

Contents?: true

Size: 1.57 KB

Versions: 2

Compression:

Stored size: 1.57 KB

Contents

# encoding: utf-8

module Informator

  # Builds, collects and publishes events to selected subscribers
  #
  # @example
  #   reporter = Reporter.new
  #   reporter.events # => []
  #
  #   reporter.remember :success
  #   reporter.events # => [#<Event @type=:success @data={} @messages=[]>]
  #
  #   # this will call subscriber.notify for any event
  #   reporter.notify subscriber
  #   reporter.events # => []
  #
  # @api private
  #
  class Reporter

    # @private
    def initialize
      @events = []
      freeze
    end

    # @!attribute [r] events
    # @return [Array<Informator::Event>]
    #   the list of registered events that havent'b been published yet
    attr_reader :events

    # @!method remember(type, messages, data)
    # Registers the event to be published to subscribers
    #
    # @param (see Informator::Event.new)
    #
    # @return [self] itself
    #
    def remember(*args)
      events << Event.new(*args)

      self
    end

    # Notifies subscribers on events registered since the last notification
    #
    # Mutates [#events] by excluding all events having been published.
    #
    # @param [Informator::Subscriber, Array<Informator::Subscriber>] subscribers
    #   the list of subscribers to be notified
    #
    # @return [Array<Informator::Event>] the list of published events
    def notify(*subscribers)
      events.dup.each { publish subscribers.flatten }
    end

    private

    def publish(subscribers)
      event = events.shift
      subscribers.each { |subscriber| subscriber.notify event }
    end

  end # class Reporter

end # module Informator

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
informator-0.0.2 lib/informator/reporter.rb
informator-0.0.1 lib/informator/reporter.rb