Module: Models::EventPublishable

Extended by:
ActiveSupport::Concern
Included in:
ApplicationRecord, EmailTemplate, ItemRelation, SmsMessage
Defined in:
app/concerns/models/event_publishable.rb

Overview

ActiveSupport::Concern mixin: event publishable.

Instance Method Summary collapse

Instance Method Details

#publish_event(event_class, data:, stream_name: "#{self.class.name}-#{id}") ⇒ Object

Publishes an event to the event store after the current database
transaction commits. Rails 7.2's after_all_transactions_commit
guarantees the event is not dispatched if the surrounding transaction
rolls back, and runs immediately if no transaction is open.

Usage:
publish_event(Events::ArticlePublished, data: { article_id: id })
publish_event(Events::ThingHappened, data: { id: id }, stream_name: "Custom-#id")



17
18
19
20
21
22
23
24
# File 'app/concerns/models/event_publishable.rb', line 17

def publish_event(event_class, data:, stream_name: "#{self.class.name}-#{id}")
  ActiveRecord.after_all_transactions_commit do
    Rails.configuration.event_store.publish(
      event_class.new(data: data),
      stream_name: stream_name
    )
  end
end