6

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

Drew
  • 15,158
  • 17
  • 68
  • 77
  • 1
    Are these listeners going to be separate processes or are they simple code blocks that can be called during the data publishing? – Nemo157 Jan 14 '11 at 21:52
  • Probably simple code blocks 80% of the time. Separate processes would be the rarer case but still probably would occur. – Drew Jan 14 '11 at 21:55

4 Answers4

6

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/

catch22
  • 1,564
  • 1
  • 18
  • 41
Adam Harte
  • 10,369
  • 7
  • 52
  • 85
5

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.

superluminary
  • 47,086
  • 25
  • 151
  • 148
Shaun
  • 4,789
  • 3
  • 22
  • 27
  • This is very close but not everything that will be published is an ActiveRecord. How would I do something similar without it being tied to ActiveRecord? – Drew Jan 14 '11 at 21:54
  • You can always bring in the ActiveRecord functionality into a non-ActiveRecord class by including ActiveRecord:Observer. More information here: http://yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/ – Shaun Jan 14 '11 at 22:03
3

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.

rewritten
  • 16,280
  • 2
  • 47
  • 50
1

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.