Sha256: ff2868661f43f3649c9eecd23e2bc9c384a8cbce5e3e81551f7487ccea8896eb

Contents?: true

Size: 1.21 KB

Versions: 3

Compression:

Stored size: 1.21 KB

Contents

# frozen_string_literal: true

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)
        super()
        @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

3 entries across 3 versions & 1 rubygems

Version Path
dry-events-1.0.1 lib/dry/events/listener.rb
dry-events-1.0.0 lib/dry/events/listener.rb
dry-events-0.4.0 lib/dry/events/listener.rb