Skip to content

Instantly share code, notes, and snippets.

@sishen
Created May 10, 2012 03:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sishen/2650824 to your computer and use it in GitHub Desktop.
Save sishen/2650824 to your computer and use it in GitHub Desktop.
Controller Observer: It's very similar like Sweeper but the observer should be manually added into config/application.rb. The benefit is that the observe still can be callable in the non-request environment such as console or rake.
# In Controller such as comments_controller.rb
observer :comment_observer, only: [:create, :destroy]
module ControllerObserver
extend ActiveSupport::Concern
module ClassMethods #:nodoc:
def observer(*observers)
configuration = observers.extract_options!
observers.each do |observer|
observer_instance = (observer.is_a?(Symbol) ? Object.const_get(observer.to_s.classify) : observer).instance
around_filter(observer_instance, :only => configuration[:only])
end
end
end
end
class CommentObserver < ActionController::Caching::Sweeper
def current_user
controller ? controller.send(:current_user) : nil
end
end
# In Controller such as comments_controller.rb
observer :comment_observer, only: [:create, :destroy]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment