All Projects → krisleech → Wisper

krisleech / Wisper

A micro library providing Ruby objects with Publish-Subscribe capabilities

Programming Languages

ruby
36898 projects - #4 most used programming language
shell
77523 projects

Projects that are alternatives of or similar to Wisper

angular-PubSub
Angular 1.x implementation of the Publish–Subscribe pattern.
Stars: ✭ 32 (-98.94%)
Mutual labels:  events, pubsub, publish-subscribe
cloudenvoy
Cross-application messaging for Ruby and Rails using Google Cloud Pub/Sub
Stars: ✭ 31 (-98.97%)
Mutual labels:  pubsub, publish-subscribe
evon
Fast and versatile event dispatcher code generator for Golang
Stars: ✭ 15 (-99.5%)
Mutual labels:  events, pubsub
uorb
C++ inter-thread publish/subscribe middleware ported from PX4 and redesigned based on POSIX
Stars: ✭ 35 (-98.84%)
Mutual labels:  pubsub, publish-subscribe
Rocketman
🚀 Rocketman help build event-based/pub-sub code in Ruby
Stars: ✭ 139 (-95.39%)
Mutual labels:  events, pubsub
Go Sdk
Dapr SDK for go
Stars: ✭ 149 (-95.06%)
Mutual labels:  events, pubsub
dead-simple
💀💡 Dead simple PubSub and EventEmitter in JavaScript
Stars: ✭ 21 (-99.3%)
Mutual labels:  events, pubsub
Open62541
Open source implementation of OPC UA (OPC Unified Architecture) aka IEC 62541 licensed under Mozilla Public License v2.0
Stars: ✭ 1,643 (-45.49%)
Mutual labels:  pubsub, publish-subscribe
dry-events
Pub/sub system
Stars: ✭ 102 (-96.62%)
Mutual labels:  events, pubsub
pg-pubsub
Reliable PostgreSQL LISTEN/NOTIFY with inter-process lock support
Stars: ✭ 50 (-98.34%)
Mutual labels:  events, pubsub
talek
a Private Publish Subscribe System
Stars: ✭ 39 (-98.71%)
Mutual labels:  pubsub, publish-subscribe
Samples
Community driven repository for Dapr samples
Stars: ✭ 104 (-96.55%)
Mutual labels:  events, pubsub
Twitchlib
C# Twitch Chat, Whisper, API and PubSub Library. Allows for chatting, whispering, stream event subscription and channel/account modification. Supports .NET Core 2.0
Stars: ✭ 519 (-82.78%)
Mutual labels:  events, pubsub
micro-typed-events
The smallest, most convenient typesafe TS event emitter you'll ever need
Stars: ✭ 39 (-98.71%)
Mutual labels:  events, pubsub
Pg Listen
📡 PostgreSQL LISTEN & NOTIFY for node.js that finally works.
Stars: ✭ 348 (-88.45%)
Mutual labels:  events, pubsub
SEPA
Get notifications about changes in your SPARQL endpoint.
Stars: ✭ 21 (-99.3%)
Mutual labels:  events, publish-subscribe
payload
A javascript single page application (SPA) driver for REST API payload management.
Stars: ✭ 16 (-99.47%)
Mutual labels:  pubsub, publish-subscribe
watermill-amqp
AMQP Pub/Sub for the Watermill project.
Stars: ✭ 27 (-99.1%)
Mutual labels:  events, pubsub
watermill-http
HTTP Pub/Sub for the Watermill project.
Stars: ✭ 16 (-99.47%)
Mutual labels:  events, pubsub
OpenCQRS
.NET Standard framework to create simple and clean design. Advanced features for DDD, CQRS and Event Sourcing.
Stars: ✭ 546 (-81.88%)
Mutual labels:  events

Wisper

A micro library providing Ruby objects with Publish-Subscribe capabilities

Gem Version Code Climate Build Status Coverage Status

  • Decouple core business logic from external concerns in Hexagonal style architectures
  • Use as an alternative to ActiveRecord callbacks and Observers in Rails apps
  • Connect objects based on context without permanence
  • Publish events synchronously or asynchronously

Note: Wisper was originally extracted from a Rails codebase but is not dependant on Rails.

Please also see the Wiki for more additional information and articles.

For greenfield applications you might also be interested in WisperNext and Ma.

Installation

Add this line to your application's Gemfile:

gem 'wisper', '2.0.0'

Usage

Any class with the Wisper::Publisher module included can broadcast events to subscribed listeners. Listeners subscribe, at runtime, to the publisher.

Publishing

class CancelOrder
  include Wisper::Publisher

  def call(order_id)
    order = Order.find_by_id(order_id)

    # business logic...

    if order.cancelled?
      broadcast(:cancel_order_successful, order.id)
    else
      broadcast(:cancel_order_failed, order.id)
    end
  end
end

When a publisher broadcasts an event it can include any number of arguments.

The broadcast method is also aliased as publish.

You can also include Wisper.publisher instead of Wisper::Publisher.

Subscribing

Objects

Any object can be subscribed as a listener.

cancel_order = CancelOrder.new

cancel_order.subscribe(OrderNotifier.new)

cancel_order.call(order_id)

The listener would need to implement a method for every event it wishes to receive.

class OrderNotifier
  def cancel_order_successful(order_id)
    order = Order.find_by_id(order_id)

    # notify someone ...
  end
end

Blocks

Blocks can be subscribed to single events and can be chained.

cancel_order = CancelOrder.new

cancel_order.on(:cancel_order_successful) { |order_id| ... }
            .on(:cancel_order_failed)     { |order_id| ... }

cancel_order.call(order_id)

You can also subscribe to multiple events using on by passing additional events as arguments.

cancel_order = CancelOrder.new

cancel_order.on(:cancel_order_successful) { |order_id| ... }
            .on(:cancel_order_failed,
                :cancel_order_invalid)    { |order_id| ... }

cancel_order.call(order_id)

Do not return from inside a subscribed block, due to the way Ruby treats blocks this will prevent any subsequent listeners having their events delivered.

Handling Events Asynchronously

cancel_order.subscribe(OrderNotifier.new, async: true)

Wisper has various adapters for asynchronous event handling, please refer to wisper-celluloid, wisper-sidekiq, wisper-activejob, wisper-que or wisper-resque.

Depending on the adapter used the listener may need to be a class instead of an object. In this situation, every method corresponding to events should be declared as a class method, too. For example:

class OrderNotifier
  # declare a class method if you are subscribing the listener class instead of its instance like:
  #   cancel_order.subscribe(OrderNotifier)
  #
  def self.cancel_order_successful(order_id)
    order = Order.find_by_id(order_id)

    # notify someone ...
  end
end

ActionController

class CancelOrderController < ApplicationController

  def create
    cancel_order = CancelOrder.new

    cancel_order.subscribe(OrderMailer,        async: true)
    cancel_order.subscribe(ActivityRecorder,   async: true)
    cancel_order.subscribe(StatisticsRecorder, async: true)

    cancel_order.on(:cancel_order_successful) { |order_id| redirect_to order_path(order_id) }
    cancel_order.on(:cancel_order_failed)     { |order_id| render action: :new }

    cancel_order.call(order_id)
  end
end

ActiveRecord

If you wish to publish directly from ActiveRecord models you can broadcast events from callbacks:

class Order < ActiveRecord::Base
  include Wisper::Publisher

  after_commit     :publish_creation_successful, on: :create
  after_validation :publish_creation_failed,     on: :create

  private

  def publish_creation_successful
    broadcast(:order_creation_successful, self)
  end

  def publish_creation_failed
    broadcast(:order_creation_failed, self) if errors.any?
  end
end

There are more examples in the Wiki.

Global Listeners

Global listeners receive all broadcast events which they can respond to.

This is useful for cross cutting concerns such as recording statistics, indexing, caching and logging.

Wisper.subscribe(MyListener.new)

In a Rails app you might want to add your global listeners in an initializer.

Global listeners are threadsafe. Subscribers will receive events published on all threads.

Scoping by publisher class

You might want to globally subscribe a listener to publishers with a certain class.

Wisper.subscribe(MyListener.new, scope: :MyPublisher)
Wisper.subscribe(MyListener.new, scope: MyPublisher)
Wisper.subscribe(MyListener.new, scope: "MyPublisher")
Wisper.subscribe(MyListener.new, scope: [:MyPublisher, :MyOtherPublisher])

This will subscribe the listener to all instances of the specified class(es) and their subclasses.

Alternatively you can also do exactly the same with a publisher class itself:

MyPublisher.subscribe(MyListener.new)

Temporary Global Listeners

You can also globally subscribe listeners for the duration of a block.

Wisper.subscribe(MyListener.new, OtherListener.new) do
  # do stuff
end

Any events broadcast within the block by any publisher will be sent to the listeners.

This is useful for capturing events published by objects to which you do not have access in a given context.

Temporary Global Listeners are threadsafe. Subscribers will receive events published on the same thread.

Subscribing to selected events

By default a listener will get notified of all events it can respond to. You can limit which events a listener is notified of by passing a string, symbol, array or regular expression to on:

post_creator.subscribe(PusherListener.new, on: :create_post_successful)

Prefixing broadcast events

If you would prefer listeners to receive events with a prefix, for example on, you can do so by passing a string or symbol to prefix:.

post_creator.subscribe(PusherListener.new, prefix: :on)

If post_creator were to broadcast the event post_created the subscribed listeners would receive on_post_created. You can also pass true which will use the default prefix, "on".

Mapping an event to a different method

By default the method called on the listener is the same as the event broadcast. However it can be mapped to a different method using with:.

report_creator.subscribe(MailResponder.new, with: :successful)

This is pretty useless unless used in conjunction with on:, since all events will get mapped to :successful. Instead you might do something like this:

report_creator.subscribe(MailResponder.new, on:   :create_report_successful,
                                            with: :successful)

If you pass an array of events to on: each event will be mapped to the same method when with: is specified. If you need to listen for select events and map each one to a different method subscribe the listener once for each mapping:

report_creator.subscribe(MailResponder.new, on:   :create_report_successful,
                                            with: :successful)

report_creator.subscribe(MailResponder.new, on:   :create_report_failed,
                                            with: :failed)

You could also alias the method within your listener, as such alias successful create_report_successful.

Testing

Testing matchers and stubs are in separate gems.

Clearing Global Listeners

If you use global listeners in non-feature tests you might want to clear them in a hook to prevent global subscriptions persisting between tests.

after { Wisper.clear }

Need help?

The Wiki has more examples, articles and talks.

Got a specific question, try the Wisper tag on StackOverflow.

Compatibility

Tested with MRI 2.x, JRuby and Rubinius.

See the build status for details.

Running Specs

bundle exec rspec

To run the specs on code changes try entr:

ls **/*.rb | entr bundle exec rspec

Contributing

Please read the Contributing Guidelines.

Security

License

(The MIT License)

Copyright (c) 2013 Kris Leech

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].