• Stars
    star
    3,266
  • Rank 13,752 (Top 0.3 %)
  • Language
    Ruby
  • Created over 11 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A micro library providing Ruby objects with Publish-Subscribe capabilities

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 like:

# config/initializers/listeners.rb
Rails.application.reloader.to_prepare do
  Wisper.subscribe(MyListener.new)
end

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

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.

More Repositories

1

vimfiles

Ruby/Rails centric vimfiles with support for Git, RVM and more.
Vim Script
182
star
2

wisper-activerecord

Transparently publish all model changes to subscribers
Ruby
100
star
3

wisper-sidekiq

Asynchronous event publishing for Wisper using Sidekiq
Ruby
82
star
4

wisper-rspec

RSpec matchers and stubbing for Wisper
Ruby
61
star
5

not_found

Allows you to rescue ActiveRecord::RecordNotFound for a specific model
Ruby
60
star
6

chalk_dust

Subscriptions connect models, events build activity feeds.
Ruby
47
star
7

wisper-activejob

Provides asynchronous event publishing to Wisper using ActiveJob
Ruby
36
star
8

evented

Publish and Subscribe for Crystal objects
Crystal
34
star
9

wisper-async

Async broadcasting for Wisper
Ruby
34
star
10

wisper-celluloid

Provides async event broadcasting to Wisper using Celluloid
Ruby
17
star
11

turbo-vim

Vim with support for Tmux, Ruby/Rails, Rspec, Git and RVM.
Vim Script
12
star
12

tmuxinator

Generate tmux configurations for your projects
Ruby
11
star
13

medicine

Simple dependency injection for Ruby objects
Ruby
7
star
14

jQuery-Character-Counter

Count and Limit the number of characters in a <textarea>
JavaScript
6
star
15

neovim-config

My NeoVIM configuration
Vim Script
5
star
16

Git-Web

A web interface for Git Repositories
Ruby
4
star
17

wisper-message_bus

Relay Wisper events as JSON to other processes via MessageBus
Ruby
4
star
18

axe

A small stream processing framework for routing Kafka topics to parallelised Ruby objects.
Ruby
4
star
19

seeds

Generate seeds.rb file from existing database tables
Ruby
4
star
20

wisper-attributes

Transparently publish attribute changes to subscribers
Ruby
4
star
21

wisper-testing

Helpers for testing Wisper publisher/subscribers.
Ruby
4
star
22

Install-Gems

Install gems listed in a text file generated by 'gem list'. Useful after doing a clean OS install.
3
star
23

conduit

An event store for Ruby
Ruby
3
star
24

vim_switcher

Switch between multiple vimfiles
Ruby
3
star
25

ma

Event Driven Ruby [MIRROR]
Ruby
3
star
26

Reinstall-Gems

Reinstall all your gems which have C extensions, useful for upgrading to 64 bit, ie. Mac 10.6 Snow Leopard
3
star
27

wisper-visualize

Visualizations for Wisper events
Ruby
3
star
28

wisper-rabbitmq

Relay Wisper events to RabbitMQ
Ruby
2
star
29

spec_requirer

Explicitly require files and manage LOAD_PATH in tests which do not boot a framework
Ruby
2
star
30

wisper_next

The next version of Wisper [MIRROR]
Ruby
2
star
31

backup_data

Engine style plugin which offers backup of database and files
Ruby
2
star
32

harbour

Terminate process listening on a port
Ruby
2
star
33

skeletor

A starting point for a Rails app which uses qcore and qcms gems
JavaScript
2
star
34

Persistent-Hash

Simple example used to teach several Ruby coding techniques
Ruby
2
star
35

wisper-relay

Relay wisper events to the outside world, for example a message queue.
Ruby
2
star
36

pipes

Toy app using pipes to communicate between two processes.
Shell
2
star
37

qwerty

This is a work in progress
Ruby
2
star
38

rake-deploy

Automated deploy and backup for Rails Application
1
star
39

qcms

Qwerty CMS (Rails Engine distributed as a Gem)
Ruby
1
star
40

Pushy

Demonstrates the use of long lived HTTP connections to allow the server (Sinatra) to *push* data to the client (JQuery)
JavaScript
1
star
41

wisper-presentation

Presentation about Wisper gem using Vim
Vim Script
1
star
42

qcore

Qwerty Core - authorisation and authentication in a Rails engine in a Gem
Ruby
1
star
43

detachment

Transparent Sub / Pub broker for Ruby objects
Ruby
1
star
44

s_and_c

One letter aliases for Rails Server and Console
Ruby
1
star
45

domain3

Service, Form and Validator objects.
Ruby
1
star
46

polymorphia

Associate any ActiveRecord object to another
Ruby
1
star
47

wisper-bubble

Event bubbling for Wisper
Ruby
1
star
48

Git-By-Proxy

Simple rake tasks to rope in a graphic designer who doesn't want to use version control and (S)FTP's stuff up to the server instead.
1
star
49

pomodoro

Promodoro timer in your shell
Ruby
1
star
50

WebbyGen

Generate skeleton directory structure plus files for a Webby site
1
star
51

scnsht

Take screenshot (selection), copy to Dropbox public folder, copy URL to clipboard
Shell
1
star
52

rails-stack

Rails stack for solo server using Sprinkle
Ruby
1
star
53

jukebox

Jukebox service
Ruby
1
star
54

QwertyChef

Chef Solo Provisioning for Rails
Ruby
1
star
55

Path-Finder

A Rails plugin which extends ActiveRecord to allow self-referential models (eg. acts_as_tree) to maintain a textual path representing itself and its ancestors.
Ruby
1
star