Sha256: d9cd9a3bbdc4138146e6c48ca6a3110ef56b97117d7e577b79d202ce202165bf

Contents?: true

Size: 1.66 KB

Versions: 31

Compression:

Stored size: 1.66 KB

Contents

---
permalink: /docs/routing_and_handlers/
title: "Routing and handlers"
toc: true
---
## Handlers

A handler is a piece of code that does something with a message.
There is no module or superclass that you need to use to implement a handler.
All that is needed is something that responds to .call with one argument, the message.

The following class can serve as a typical handler:

```ruby
class NotifyCompetingBidders
  def self.call(bid_placed)
    other_bidders.each { |bidder| SendOutbidNotice.call(recipient: bidder) }
  end
end
```

But a handler can also be a plain block in a route:
```ruby
class HandleBiddingEvents
  include Messaging::Routing

  def self.call(message)
    new.handle(message)
  end

  # A block used as a handler
  on BidPlaced do |bid_placed|
    log_bid_event bid_placed
  end
end
```

## Routing

There are multiple ways to route messages to handlers.


### Synchronous handlers
Use the call: keyword in a route to make the handler synchronous.
```ruby
Messaging.routes.draw do
  on Events::BidPlaced, call: NotifyCompetingBidders
end
```
**Be aware!** The handler would trigger in the same thread as the code that publishes the event.
This may or may not be a problem. But think twice before using synchronous handlers.
{: .notice}

### Enqueued handlers
Use the enqueue: keyword to make a handler be called by a background worker like Sidekiq.
```ruby
Messaging.routes.draw do
  on Events::BidPlaced, enqueue: NotifyCompetingBidders
end
```
**Be aware!** Sidekiq / Resque / ActiveJob does not guarantee that the jobs will be
processed in any specific order. If the order in which handlers gets called is important
you should probably use a Consumer instead
{: .notice}

Version data entries

31 entries across 31 versions & 1 rubygems

Version Path
messaging-4.0.12 docs/routing_and_handlers.md
messaging-4.0.11 docs/routing_and_handlers.md
messaging-4.0.10 docs/routing_and_handlers.md
messaging-4.0.10.pre docs/routing_and_handlers.md
messaging-4.0.9 docs/routing_and_handlers.md
messaging-4.0.8 docs/routing_and_handlers.md
messaging-4.0.7 docs/routing_and_handlers.md
messaging-4.0.6 docs/routing_and_handlers.md
messaging-4.0.5 docs/routing_and_handlers.md
messaging-4.0.4.pre docs/routing_and_handlers.md
messaging-4.0.3.pre docs/routing_and_handlers.md
messaging-4.0.2.pre docs/routing_and_handlers.md
messaging-4.0.1.pre docs/routing_and_handlers.md
messaging-4.0.0.pre docs/routing_and_handlers.md
messaging-3.8.2 docs/routing_and_handlers.md
messaging-3.8.1 docs/routing_and_handlers.md
messaging-3.8.0 docs/routing_and_handlers.md
messaging-3.7.3 docs/routing_and_handlers.md
messaging-3.7.2 docs/routing_and_handlers.md
messaging-3.7.1 docs/routing_and_handlers.md