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.



97
98
99
# File 'lib/dry/events/publisher.rb', line 97

def initialize(id)
  @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



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

attr_reader :id

#idObject (readonly)



80
81
82
# File 'lib/dry/events/publisher.rb', line 80

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



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

def self.[](id)
  raise PublisherAlreadyRegisteredError.new(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.



73
74
75
# File 'lib/dry/events/publisher.rb', line 73

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



106
107
108
109
110
111
112
113
# File 'lib/dry/events/publisher.rb', line 106

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

  self.class.registry[id] = klass

  super
end