{"id":13411651,"url":"https://github.com/krisleech/wisper","last_synced_at":"2025-05-12T13:28:10.482Z","repository":{"id":7741897,"uuid":"9108797","full_name":"krisleech/wisper","owner":"krisleech","description":"A micro library providing Ruby objects with Publish-Subscribe capabilities","archived":false,"fork":false,"pushed_at":"2024-08-15T15:29:18.000Z","size":327,"stargazers_count":3301,"open_issues_count":2,"forks_count":154,"subscribers_count":48,"default_branch":"master","last_synced_at":"2025-05-07T11:11:23.413Z","etag":null,"topics":["events","publish-subscribe","pubsub","ruby"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/krisleech.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2013-03-29T23:48:32.000Z","updated_at":"2025-05-04T03:54:07.000Z","dependencies_parsed_at":"2023-02-19T13:45:21.908Z","dependency_job_id":"ae3a5567-af29-4049-8504-2eae8e67222f","html_url":"https://github.com/krisleech/wisper","commit_stats":{"total_commits":232,"total_committers":45,"mean_commits":5.155555555555556,"dds":0.3318965517241379,"last_synced_commit":"4569343e353e8f070bd8219527f6eb9703bce653"},"previous_names":[],"tags_count":15,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/krisleech%2Fwisper","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/krisleech%2Fwisper/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/krisleech%2Fwisper/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/krisleech%2Fwisper/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/krisleech","download_url":"https://codeload.github.com/krisleech/wisper/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253059836,"owners_count":21847386,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["events","publish-subscribe","pubsub","ruby"],"created_at":"2024-07-30T20:01:15.404Z","updated_at":"2025-05-12T13:28:10.464Z","avatar_url":"https://github.com/krisleech.png","language":"Ruby","readme":"# Wisper\n\n*A micro library providing Ruby objects with Publish-Subscribe capabilities*\n\n[![Gem Version](https://badge.fury.io/rb/wisper.svg)](http://badge.fury.io/rb/wisper)\n[![Code Climate](https://codeclimate.com/github/krisleech/wisper.svg)](https://codeclimate.com/github/krisleech/wisper)\n[![Build Status](https://github.com/krisleech/wisper/actions/workflows/test.yml/badge.svg)](https://github.com/krisleech/wisper/actions)\n[![Coverage Status](https://coveralls.io/repos/krisleech/wisper/badge.svg?branch=master)](https://coveralls.io/r/krisleech/wisper?branch=master)\n\n* Decouple core business logic from external concerns in Hexagonal style architectures\n* Use as an alternative to ActiveRecord callbacks and Observers in Rails apps\n* Connect objects based on context without permanence\n* Publish events synchronously or asynchronously\n\nNote: Wisper was originally extracted from a Rails codebase but is not dependent on Rails.\n\nPlease also see the [Wiki](https://github.com/krisleech/wisper/wiki) for more additional information and articles.\n\n**For greenfield applications you might also be interested in\n[WisperNext](https://gitlab.com/kris.leech/wisper_next) and [Ma](https://gitlab.com/kris.leech/ma).**\n\n## Installation\n\nAdd this line to your application's Gemfile:\n\n```ruby\ngem 'wisper', '~\u003e 3.0'\n```\n\n## Usage\n\nAny class with the `Wisper::Publisher` module included can broadcast events\nto subscribed listeners. Listeners subscribe, at runtime, to the publisher.\n\n### Publishing\n\n```ruby\nclass CancelOrder\n  include Wisper::Publisher\n\n  def call(order_id)\n    order = Order.find_by_id(order_id)\n\n    # business logic...\n\n    if order.cancelled?\n      broadcast(:cancel_order_successful, order.id)\n    else\n      broadcast(:cancel_order_failed, order.id)\n    end\n  end\nend\n```\n\nWhen a publisher broadcasts an event it can include any number of arguments.\n\nThe `broadcast` method is also aliased as `publish`.\n\nYou can also include `Wisper.publisher` instead of `Wisper::Publisher`.\n\n### Subscribing\n\n#### Objects\n\nAny object can be subscribed as a listener.\n\n```ruby\ncancel_order = CancelOrder.new\n\ncancel_order.subscribe(OrderNotifier.new)\n\ncancel_order.call(order_id)\n```\n\nThe listener would need to implement a method for every event it wishes to receive.\n\n```ruby\nclass OrderNotifier\n  def cancel_order_successful(order_id)\n    order = Order.find_by_id(order_id)\n\n    # notify someone ...\n  end\nend\n```\n\n#### Blocks\n\nBlocks can be subscribed to single events and can be chained.\n\n```ruby\ncancel_order = CancelOrder.new\n\ncancel_order.on(:cancel_order_successful) { |order_id| ... }\n            .on(:cancel_order_failed)     { |order_id| ... }\n\ncancel_order.call(order_id)\n```\n\nYou can also subscribe to multiple events using `on` by passing\nadditional events as arguments.\n\n```ruby\ncancel_order = CancelOrder.new\n\ncancel_order.on(:cancel_order_successful) { |order_id| ... }\n            .on(:cancel_order_failed,\n                :cancel_order_invalid)    { |order_id| ... }\n\ncancel_order.call(order_id)\n```\n\nDo not `return` from inside a subscribed block, due to the way\n[Ruby treats blocks](http://product.reverb.com/2015/02/28/the-strange-case-of-wisper-and-ruby-blocks-behaving-like-procs/)\nthis will prevent any subsequent listeners having their events delivered.\n\n### Handling Events Asynchronously\n\n```ruby\ncancel_order.subscribe(OrderNotifier.new, async: true)\n```\n\nWisper has various adapters for asynchronous event handling, please refer to\n[wisper-celluloid](https://github.com/krisleech/wisper-celluloid),\n[wisper-sidekiq](https://github.com/krisleech/wisper-sidekiq),\n[wisper-activejob](https://github.com/krisleech/wisper-activejob),\n[wisper-que](https://github.com/joevandyk/wisper-que) or\n[wisper-resque](https://github.com/bzurkowski/wisper-resque).\n\nDepending 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:\n\n```ruby\nclass OrderNotifier\n  # declare a class method if you are subscribing the listener class instead of its instance like:\n  #   cancel_order.subscribe(OrderNotifier)\n  #\n  def self.cancel_order_successful(order_id)\n    order = Order.find_by_id(order_id)\n\n    # notify someone ...\n  end\nend\n```\n\n### ActionController\n\n```ruby\nclass CancelOrderController \u003c ApplicationController\n\n  def create\n    cancel_order = CancelOrder.new\n\n    cancel_order.subscribe(OrderMailer,        async: true)\n    cancel_order.subscribe(ActivityRecorder,   async: true)\n    cancel_order.subscribe(StatisticsRecorder, async: true)\n\n    cancel_order.on(:cancel_order_successful) { |order_id| redirect_to order_path(order_id) }\n    cancel_order.on(:cancel_order_failed)     { |order_id| render action: :new }\n\n    cancel_order.call(order_id)\n  end\nend\n```\n\n### ActiveRecord\n\nIf you wish to publish directly from ActiveRecord models you can broadcast events from callbacks:\n\n```ruby\nclass Order \u003c ActiveRecord::Base\n  include Wisper::Publisher\n\n  after_commit     :publish_creation_successful, on: :create\n  after_validation :publish_creation_failed,     on: :create\n\n  private\n\n  def publish_creation_successful\n    broadcast(:order_creation_successful, self)\n  end\n\n  def publish_creation_failed\n    broadcast(:order_creation_failed, self) if errors.any?\n  end\nend\n```\n\nThere are more examples in the [Wiki](https://github.com/krisleech/wisper/wiki).\n\n## Global Listeners\n\nGlobal listeners receive all broadcast events which they can respond to.\n\nThis is useful for cross cutting concerns such as recording statistics, indexing, caching and logging.\n\n```ruby\nWisper.subscribe(MyListener.new)\n```\n\nIn a Rails app you might want to add your global listeners in an initializer like:\n\n```ruby\n# config/initializers/listeners.rb\nRails.application.reloader.to_prepare do\n  Wisper.clear if Rails.env.development?\n\n  Wisper.subscribe(MyListener.new)\nend\n```\n\nGlobal listeners are threadsafe. Subscribers will receive events published on all threads.\n\n\n### Scoping by publisher class\n\nYou might want to globally subscribe a listener to publishers with a certain\nclass.\n\n```ruby\nWisper.subscribe(MyListener.new, scope: :MyPublisher)\nWisper.subscribe(MyListener.new, scope: MyPublisher)\nWisper.subscribe(MyListener.new, scope: \"MyPublisher\")\nWisper.subscribe(MyListener.new, scope: [:MyPublisher, :MyOtherPublisher])\n```\n\nThis will subscribe the listener to all instances of the specified class(es) and their\nsubclasses.\n\nAlternatively you can also do exactly the same with a publisher class itself:\n\n```ruby\nMyPublisher.subscribe(MyListener.new)\n```\n\n## Temporary Global Listeners\n\nYou can also globally subscribe listeners for the duration of a block.\n\n```ruby\nWisper.subscribe(MyListener.new, OtherListener.new) do\n  # do stuff\nend\n```\n\nAny events broadcast within the block by any publisher will be sent to the\nlisteners.\n\nThis is useful for capturing events published by objects to which you do not have access in a given context.\n\nTemporary Global Listeners are threadsafe. Subscribers will receive events published on the same thread.\n\n## Subscribing to selected events\n\nBy default a listener will get notified of all events it can respond to. You\ncan limit which events a listener is notified of by passing a string, symbol,\narray or regular expression to `on`:\n\n```ruby\npost_creator.subscribe(PusherListener.new, on: :create_post_successful)\n```\n\n## Prefixing broadcast events\n\nIf you would prefer listeners to receive events with a prefix, for example\n`on`, you can do so by passing a string or symbol to `prefix:`.\n\n```ruby\npost_creator.subscribe(PusherListener.new, prefix: :on)\n```\n\nIf `post_creator` were to broadcast the event `post_created` the subscribed\nlisteners would receive `on_post_created`. You can also pass `true` which will\nuse the default prefix, \"on\".\n\n## Mapping an event to a different method\n\nBy default the method called on the listener is the same as the event\nbroadcast. However it can be mapped to a different method using `with:`.\n\n```ruby\nreport_creator.subscribe(MailResponder.new, with: :successful)\n```\n\nThis is pretty useless unless used in conjunction with `on:`, since all events\nwill get mapped to `:successful`. Instead you might do something like this:\n\n```ruby\nreport_creator.subscribe(MailResponder.new, on:   :create_report_successful,\n                                            with: :successful)\n```\n\nIf you pass an array of events to `on:` each event will be mapped to the same\nmethod when `with:` is specified. If you need to listen for select events\n_and_ map each one to a different method subscribe the listener once for\neach mapping:\n\n```ruby\nreport_creator.subscribe(MailResponder.new, on:   :create_report_successful,\n                                            with: :successful)\n\nreport_creator.subscribe(MailResponder.new, on:   :create_report_failed,\n                                            with: :failed)\n```\n\nYou could also alias the method within your listener, as such\n`alias successful create_report_successful`.\n\n## Testing\n\nTesting matchers and stubs are in separate gems.\n\n* [wisper-rspec](https://github.com/krisleech/wisper-rspec)\n* [wisper-minitest](https://github.com/digitalcuisine/wisper-minitest)\n\n### Clearing Global Listeners\n\nIf you use global listeners in non-feature tests you _might_ want to clear them\nin a hook to prevent global subscriptions persisting between tests.\n\n```ruby\nafter { Wisper.clear }\n```\n\n## Need help?\n\nThe [Wiki](https://github.com/krisleech/wisper/wiki) has more examples,\narticles and talks.\n\nGot a specific question, try the\n[Wisper tag on StackOverflow](http://stackoverflow.com/questions/tagged/wisper).\n\n## Compatibility\n\nSee the [build status](https://github.com/krisleech/wisper/actions) for details.\n\n## Running Specs\n\n```\nbundle exec rspec\n```\n\nTo run the specs on code changes try [entr](http://entrproject.org/):\n\n```\nls **/*.rb | entr bundle exec rspec\n```\n\n## Contributing\n\nPlease read the [Contributing Guidelines](https://github.com/krisleech/wisper/blob/master/CONTRIBUTING.md).\n\n## Security\n\n* gem releases are [signed](http://guides.rubygems.org/security/) ([public key](https://github.com/krisleech/wisper/blob/master/gem-public_cert.pem))\n* commits are GPG signed ([public key](https://pgp.mit.edu/pks/lookup?op=get\u0026search=0x3ABC74851F7CCC88))\n* My [Keybase.io profile](https://keybase.io/krisleech)\n\n## License\n\n(The MIT License)\n\nCopyright (c) 2013 Kris Leech\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the 'Software'), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n","funding_links":[],"categories":["Ruby","Abstraction","Business logic","Uncategorized"],"sub_categories":["Uncategorized"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkrisleech%2Fwisper","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkrisleech%2Fwisper","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkrisleech%2Fwisper/lists"}