Class: Dry::Events::Publisher

Inherits:
Module
  • Object
show all
Defined in:
lib/dry/events/publisher.rb

Overview

Extension used for classes that can publish events

Examples:

class AppEvents
  include Dry::Events::Publisher[:app]

  register_event('users.created')
end

class CreateUser
  attr_reader :events

  def initialize(events)
    @events = events
  end

  def call(user)
    # do your thing
    events.publish('users.created', user: user, time: Time.now)
  end
end

app_events = AppEvents.new
create_user = CreateUser.new(app_events)

# this will publish "users.created" event with its payload
create_user.call(name: "Jane")

Defined Under Namespace

Modules: ClassMethods, InstanceMethods

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id) ⇒ Publisher

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of Publisher.



111
112
113
114
# File 'lib/dry/events/publisher.rb', line 111

def initialize(id)
  super()
  @id = id
end

Instance Attribute Details

#:id(: id) ⇒ Symbol, String (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns the publisher identifier.

Returns:

  • (Symbol, String)

    the publisher identifier



93
# File 'lib/dry/events/publisher.rb', line 93

attr_reader :id

#idObject (readonly)



93
94
95
# File 'lib/dry/events/publisher.rb', line 93

def id
  @id
end

Class Method Details

.[](id) ⇒ Publisher

Create a publisher extension with the provided identifier

Parameters:

  • id (Symbol, String)

    The identifier

Returns:

Raises:

  • PublisherAlreadyRegisteredError



104
105
106
107
108
# File 'lib/dry/events/publisher.rb', line 104

def self.[](id)
  raise PublisherAlreadyRegisteredError, id if registry.key?(id)

  new(id)
end

.registryObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Internal publisher registry, which is used to identify them globally

This allows us to have listener classes that can subscribe to events without having access to instances of publishers yet.



86
87
88
# File 'lib/dry/events/publisher.rb', line 86

def self.registry
  @__registry__ ||= Concurrent::Map.new
end

Instance Method Details

#included(klass) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Hook for inclusions/extensions

It registers the publisher class under global registry using the id



121
122
123
124
125
126
127
128
# File 'lib/dry/events/publisher.rb', line 121

def included(klass)
  klass.extend(ClassMethods)
  klass.include(InstanceMethods)

  self.class.registry[id] = klass

  super
end