Koine::EventManager
A simple and lightweight event management library for Ruby that enables event-driven architecture through a publish-subscribe pattern.
Features
- Simple API - Easy to understand and use
- Block-based listeners - Quick inline event handlers
- Object-based subscribers - Reusable event handling objects
- Event inheritance - Listen to parent event classes and receive child events
- No dependencies - Pure Ruby implementation
- Thread-safe operations - Safe for concurrent use
Requirements
- Ruby >= 3.0
Installation
Add this line to your application's Gemfile:
gem 'koine-event_manager'
And then execute:
$ bundle install
Or install it yourself as:
$ gem install koine-event_manager
Usage
Basic Example
require 'koine/event_manager'
# Define your event
class UserSignedIn
attr_reader :user
def initialize(user)
@user = user
end
end
# Create the event manager
event_manager = Koine::EventManager::EventManager.new
# Register a listener
event_manager.listen_to(UserSignedIn) do |event|
puts "Welcome, #{event.user.name}!"
WelcomeEmail.new(event.user).send
end
# Trigger the event
user = User.find(123)
event_manager.trigger(UserSignedIn.new(user))
Block-based Listeners
Use block-based listeners for simple, inline event handlers:
event_manager = Koine::EventManager::EventManager.new
event_manager.listen_to(UserSignedIn) do |event|
WelcomeEmail.new(event.user).send
end
event_manager.listen_to(UserRemovedAccount) do |event|
CleanupJob.perform_later(event.user.id)
end
# Trigger events
event_manager.trigger(UserSignedIn.new(user))
When to use: Quick, one-off event handlers that don't need to be reused.
Event Listener Classes
For better organization, create reusable listener classes:
class UserListener < Koine::EventManager::EventListener
def initialize
super
listen_to(UserSignedIn) do |event|
WelcomeEmail.new(event.user).send
end
listen_to(UserRemovedAccount) do |event|
PleaseComeBackEmail.new(event.user).send
end
end
end
# Attach the listener to the event manager
event_manager = Koine::EventManager::EventManager.new
event_manager.attach_listener(UserListener.new)
# Trigger events
event_manager.trigger(UserSignedIn.new(some_user))
# Later, you can detach listeners if needed
event_manager.detach_listener(event_manager.listeners.last)
When to use: Related event handlers that should be grouped together and potentially attached/detached as a unit.
Subscribers
Subscribers are objects that implement a publish method. They provide a more object-oriented approach to event handling:
class NotificationSubscriber
def publish(event)
case event
when UserSignedIn
send_welcome_notification(event.user)
when UserRemovedAccount
send_goodbye_notification(event.user)
end
end
private
def send_welcome_notification(user)
# Send notification logic
end
def send_goodbye_notification(user)
# Send notification logic
end
end
# Subscribe to specific events
subscriber = NotificationSubscriber.new
event_manager.subscribe(subscriber, to: UserSignedIn)
event_manager.subscribe(subscriber, to: UserRemovedAccount)
# Trigger events - subscriber.publish(event) will be called
event_manager.trigger(UserSignedIn.new(user))
# Unsubscribe when no longer needed
event_manager.unsubscribe(subscriber, from: UserSignedIn)
When to use: Complex event handling logic that needs to be encapsulated in a class with state and multiple methods.
Event Inheritance
The event manager supports event inheritance. If you listen to a parent event class, you'll also receive events from child classes:
class UserEvent
attr_reader :user
def initialize(user)
@user = user
end
end
class UserSignedIn < UserEvent
end
class UserSignedOut < UserEvent
end
# Listen to the parent class
event_manager.listen_to(UserEvent) do |event|
puts "User event occurred for #{event.user.name}"
end
# Both of these will trigger the listener above
event_manager.trigger(UserSignedIn.new(user))
event_manager.trigger(UserSignedOut.new(user))
Using in Rails
Here's a complete example of how to use the event manager in a Rails application:
# app/events/user_signed_in.rb
class UserSignedIn
attr_reader :user, :ip_address
def initialize(user, ip_address: nil)
@user = user
@ip_address = ip_address
end
end
# app/listeners/user_listener.rb
class UserListener < Koine::EventManager::EventListener
def initialize
super
listen_to(UserSignedIn) do |event|
WelcomeMailer.welcome_email(event.user).deliver_later
TrackingService.track_login(event.user, event.ip_address)
end
end
end
# config/initializers/event_manager.rb
Rails.application.config.event_manager = Koine::EventManager::EventManager.new
Rails.application.config.event_manager.attach_listener(UserListener.new)
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
def event_manager
Rails.application.config.event_manager
end
end
# app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
def create
@user = User.find_by(email: params[:email])
if @user&.authenticate(params[:password])
session[:user_id] = @user.id
event_manager.trigger(UserSignedIn.new(@user, ip_address: request.remote_ip))
redirect_to root_path, notice: 'Signed in successfully'
else
render :new, alert: 'Invalid credentials'
end
end
end
Error Isolation
By default, an exception raised by a listener or subscriber propagates and aborts
the dispatch. Pass an on_error callback to isolate failures so the remaining
listeners still run:
event_manager = Koine::EventManager::EventManager.new(
on_error: ->(error, event:, listener:) { Bugsnag.notify(error) }
)
The callback is invoked as on_error.call(error, event:, listener:), so it must
accept the event: and listener: keyword arguments (the failing event and the
listener/subscriber that raised). Use them to attribute the failure, or ignore them
with a splat:
on_error: ->(error, **) { Bugsnag.notify(error) }
Without on_error the behavior is unchanged (errors re-raise).
Post-commit Dispatch (Rails)
require "koine/event_manager/rails" adds TransactionalEventManager, a drop-in
subclass that defers dispatch until the current database transaction commits (or
runs immediately when none is open), via ActiveRecord.after_all_transactions_commit.
This keeps listeners from reacting to changes that a rollback would undo.
require "koine/event_manager/rails"
bus = Koine::EventManager::TransactionalEventManager.new(
on_error: ->(error, **) { Bugsnag.notify(error) }
)
Requires ActiveRecord >= 7.2; the core library remains dependency-free, so only load this file from within a Rails/ActiveRecord process.
Subscribers (and block listeners) are deferred by default. A reaction that must run
inside the transaction — e.g. to write a related record atomically, or to raise
and roll the whole operation back — can opt out with after_commit: false:
bus.subscribe(AuditWriter.new, to: ProposalCreated) # post-commit, isolated
bus.subscribe(InventoryReserver.new, to: ProposalCreated, after_commit: false) # in-transaction
bus.listen_to(ProposalCreated, after_commit: false) { |e| ... } # in-transaction block
Synchronous (after_commit: false) listeners run inline and their errors propagate
(bypassing on_error), so a failed integrity reaction aborts the surrounding
transaction. Deferred listeners stay isolated by on_error.
API Reference
EventManager
EventManager.new(on_error: nil)- Optionally isolate listener errors (see Error Isolation)listen_to(event_class, &block)- Register a block to handle eventstrigger(event)- Dispatch an event to all listeners and subscriberspublish(event)- Alias fortrigger(pub/sub vocabulary)subscribe(subscriber, to: event_type)- Add a subscriber for an event typeunsubscribe(subscriber, from: event_type)- Remove a subscriberattach_listener(listener)- Attach an EventListener instancedetach_listener(listener)- Remove a listenerlisteners- Get array of attached listeners
EventListener
listen_to(event_type, &block)- Register a block handler for an event typesubscribe(subscriber, to: event_type)- Register a subscriber objectunsubscribe(subscriber, from: event_type)- Unregister a subscribertrigger(event_object)- Process the event through all listeners and subscribers
Development
After checking out the repo, run bin/setup to install dependencies. Then, run bundle exec rspec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.
Running Tests
bundle exec rspec
Running Linter
bundle exec rubocop
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/mjacobus/koine-event-manager. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.
License
The gem is available as open source under the terms of the MIT License.