Created
May 10, 2012 03:19
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# In Controller such as comments_controller.rb | |
observer :comment_observer, only: [:create, :destroy] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CommentObserver < ActionController::Caching::Sweeper | |
def current_user | |
controller ? controller.send(:current_user) : nil | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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