Permalink
Browse files

Some documentation love

  • Loading branch information...
1 parent 6c60c5b commit 7e917136fd4711ca934b14360d7e5909b7afa3de Rafael Mendonça França committed Nov 28, 2012
Showing with 75 additions and 2 deletions.
  1. +75 −2 README.md
View
@@ -1,6 +1,6 @@
# Rails::Observers
-TODO: Write a gem description
+Rails Observers (removed from core in Rails 4.0)
## Installation
@@ -18,7 +18,80 @@ Or install it yourself as:
## Usage
-TODO: Write usage instructions here
+This gem contains two observers:
+
+* Active Record Observer
+* Action Controller Sweeper
+
+### Active Record Observer
+
+Observer classes respond to life cycle callbacks to implement trigger-like
+behavior outside the original class. This is a great way to reduce the
+clutter that normally comes when the model class is burdened with
+functionality that doesn't pertain to the core responsibility of the
+class. Example:
+
+```ruby
+class CommentObserver < ActiveRecord::Observer
+ def after_save(comment)
+ Notifications.comment("admin@do.com", "New comment was posted", comment).deliver
+ end
+end
+```
+
+This Observer sends an email when a Comment#save is finished.
+
+```ruby
+class ContactObserver < ActiveRecord::Observer
+ def after_create(contact)
+ contact.logger.info('New contact added!')
+ end
+
+ def after_destroy(contact)
+ contact.logger.warn("Contact with an id of #{contact.id} was destroyed!")
+ end
+end
+```
+
+This Observer uses logger to log when specific callbacks are triggered.
+
+### Action Controller Sweeper
+
+Sweepers are the terminators of the caching world and responsible for expiring caches when model objects change.
+They do this by being half-observers, half-filters and implementing callbacks for both roles. A Sweeper example:
+
+```ruby
+class ListSweeper < ActionController::Caching::Sweeper
+ observe List, Item
+
+ def after_save(record)
+ list = record.is_a?(List) ? record : record.list
+ expire_page(:controller => "lists", :action => %w( show public feed ), :id => list.id)
+ expire_action(:controller => "lists", :action => "all")
+ list.shares.each { |share| expire_page(:controller => "lists", :action => "show", :id => share.url_key) }
+ end
+end
+```
+
+The sweeper is assigned in the controllers that wish to have its job performed using the `cache_sweeper` class method:
+
+```ruby
+class ListsController < ApplicationController
+ caches_action :index, :show, :public, :feed
+ cache_sweeper :list_sweeper, :only => [ :edit, :destroy, :share ]
+end
+```
+
+In the example above, four actions are cached and three actions are responsible for expiring those caches.
+
+You can also name an explicit class in the declaration of a sweeper, which is needed if the sweeper is in a module:
+
+```ruby
+class ListsController < ApplicationController
+ caches_action :index, :show, :public, :feed
+ cache_sweeper OpenBar::Sweeper, :only => [ :edit, :destroy, :share ]
+end
+```
## Contributing

0 comments on commit 7e91713

Please sign in to comment.