Sweeper outside?
Sometimes we modify some stuff without controllers (for example we publish some stuff via rake task ignited by cron). Unfortunately Rails does not handle it "out of the box", so we need to do it by ourselfs.
BaseSweeper
Let's create a base sweeper class where all the "magic" will happen:
class BaseSweeper < ActionController::Caching::Sweeper def after_save(data) expire_data(data) end def after_destroy(data) expire_data(data) end def expire_data @controller ||= ActionController::Base.new end end
There's nothing special about this code, except:
@controller ||= ActionController::Base.new
This line will emulate (if needed) controller outside of standard Rails flow. Thanks to this we can sweep stuff whenever we need. Example:
class NewsSweeper < BaseSweeper observe News def expire_data(data) super expire_fragment /news_#{data.id}/ end end
There's one more thing to do. We need to add sweeper to observers in application.rb file (so our sweeper will react on any change in observed model):
application.rb:
config.active_record.observers = "CommentObserver", "JakistamInnyObserver", # Sweepery "NewsSweeper"