Sha256: def95fb9ffe3daae96c29f1d22108aa0ef1fdf9356c750347689c62cb57a219d

Contents?: true

Size: 1.18 KB

Versions: 1

Compression:

Stored size: 1.18 KB

Contents

require 'dry/equalizer'
require 'dry/events/publisher'

module Dry
  module Events
    # Extension for objects that can listen to events
    #
    # @example
    #   class AppEvents
    #     include Dry::Events::Publisher[:app]
    #
    #     register_event("users.created")
    #   end

    #   class MyListener
    #     include Dry::Events::Listener[:app]
    #
    #     subscribe("users.created") do |event|
    #       # do something
    #     end
    #   end
    #
    # @api public
    class Listener < Module
      include Dry::Equalizer(:id)

      # @!attribute [r] :id
      #   @return [Symbol,String] The publisher identifier
      #   @api private
      attr_reader :id

      # Create a listener extension for a specific publisher
      #
      # @return [Module]
      #
      # @api public
      def self.[](id)
        new(id)
      end

      # @api private
      def initialize(id)
        @id = id

        define_method(:subscribe) do |event_id, query = EMPTY_HASH, &block|
          Publisher.registry[id].subscribe(event_id, query, &block)
        end
      end

      # @api private
      def included(klass)
        klass.extend(self)
        super
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
dry-events-0.1.0 lib/dry/events/listener.rb