event_machine

With event machine, you can keep an eye on any action on your rails controller, say in your sns website, when user posts a blog, you need to notice all of his friends, but it’s really urgly to do like this:

BlogController:
  def create
    # new and save code
    notice_all_friends
  end
end

let’s take another scenario, in your sns site, when one user makes friends with the other one, we should notice all friends of these two people, but how to? we’d beeter have an observer on the action, the code in the make_friends action block only concerns about building relationship between the two people, the observer then notice other people, and this is also what IoC(AOP) teach us.

Usage:

in your config/environment.rb:

gem "event_machine", :version => ">=0.2.1"

application_controller.rb:

class ApplicationController < ActionController::Base
  include EventMachine
end

and the generate command :

~your_project_path> rails g event_machine create_favorite FavoriteController create

then it will generate a event file which content like following:

for_action FavoritesController, :create do

  before do
    # This will be called before FavoriteController#create
  end

  after do
    # This will be called after FavoriteController#create
  end

end

now you can add your code in the block and after block, enjoy.

to observe multiple actions

to observe multiple actions, you should:

for_actions [[FavoritesController, :create], [BlogsController,:create]] do

  before do
    # your code goes here
  end

  after do
    # your code goes here
  end

end

Note on Patches/Pull Requests

  • Fork the project.

  • Make your feature addition or bug fix.

  • Add tests for it. This is important so I don’t break it in a future version unintentionally.

  • Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)

  • Send me a pull request. Bonus points for topic branches.

Copyright © 2010 tim.teng. See LICENSE for details.