Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event/Observer Driven Ruby on Rails

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

like image 622
Drew Avatar asked Jan 14 '11 21:01

Drew


4 Answers

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/

like image 80
Adam Harte Avatar answered Oct 13 '22 00:10

Adam Harte


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.

like image 31
Shaun Avatar answered Oct 12 '22 23:10

Shaun


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.

like image 45
rewritten Avatar answered Oct 12 '22 23:10

rewritten


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.

like image 36
M'hammed Amine Asli Avatar answered Oct 12 '22 22:10

M'hammed Amine Asli