Question

I have an application that lends itself to an event/listener model. Several different kinds of data get published (event), then many different things may or may not need to act on that data (listeners). There's no specific order the listeners need to happen in and each listener would determine whether or not it needs to act on the event.

What tools for Rails apps are there to accomplish this task? I'm hoping to not have to do this myself (although, I can. It's not THAT big a deal.)

Edit: Observer pattern might be a better choice for this

Was it helpful?

Solution

Check out EventMachine. It is a very popular event-processing library for Ruby. It looks quite good, and a lot of other libraries seem to take advantage of it (Cramp).

Here is a good introduction: http://rubylearning.com/blog/2010/10/01/an-introduction-to-eventmachine-and-how-to-avoid-callback-spaghetti/

OTHER TIPS

You'll probably want to hook into ActiveRecord's Observer class.

http://api.rubyonrails.org/v3.2.13/classes/ActiveRecord/Observer.html

With it, your models can execute custom logic for several lifecycle events:

http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

If I understand your intent correctly, all you'll need to do is call the methods that represent your listener's action to an event from those callbacks.

You may want to use ActiveSupport::Notifications.instrument.

It is a general-purpose bridge for decoupling event sending to event reacting. It's geared towards executing all listeners during a single web request, unlike EventMachine, which is geared towards having lots of concurrent things happening.

I have created a ruby gem responding exactly to this use case : event_dispatcher

This gem provides a simple observer implementation, allowing you to subscribe and listen for events in your application with a simple and effective way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top