Skip to content

Instantly share code, notes, and snippets.

@linyows
Forked from asavartsov/sweeping.rb
Created February 20, 2013 05:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save linyows/4993178 to your computer and use it in GitHub Desktop.
Save linyows/4993178 to your computer and use it in GitHub Desktop.
# 2. Include Sweeping module in your controller(s) to have cache_sweeper
# method to be avaliable, or right in ApplicationController so it will be
# available in all controllers inheriting from it.
class ApplicationController < ActionController::Base
include ActionController::Caching::Sweeping
# ...
end
# 3. Use cache sweepers as usual (http://guides.rubyonrails.org/caching_with_rails.html#sweepers)
# 1. Save this file as lib/action_controller/caching/sweeping.rb
# Ported from: https://github.com/rails/rails/blob/3-2-stable/actionpack/lib/action_controller/caching/sweeping.rb
module ActionController
module Caching
module Sweeping
extend ActiveSupport::Concern
module ClassMethods
def cache_sweeper(*sweepers)
configuration = sweepers.extract_options!
sweepers.each do |sweeper|
Mongoid.observers << sweeper if defined?(Mongoid)
sweeper_instance = (sweeper.is_a?(Symbol) ? Object.const_get(sweeper.to_s.classify) : sweeper).instance
if sweeper_instance.is_a?(Sweeper)
around_filter(sweeper_instance, :only => configuration[:only])
else
after_filter(sweeper_instance, :only => configuration[:only])
end
end
end
end
end
if defined?(Mongoid) and defined?(Mongoid::Observer)
class Sweeper < Mongoid::Observer
attr_accessor :controller
def before(controller)
self.controller = controller
callback(:before) if controller.perform_caching
true # before method from sweeper should always return true
end
def after(controller)
self.controller = controller
callback(:after) if controller.perform_caching
# Clean up, so that the controller can be collected after this request
self.controller = nil
end
protected
# gets the action cache path for the given options.
def action_path_for(options)
Actions::ActionCachePath.new(controller, options).path
end
# Retrieve instance variables set in the controller.
def assigns(key)
controller.instance_variable_get("@#{key}")
end
private
def callback(timing)
controller_callback_method_name = "#{timing}_#{controller.controller_name.underscore}"
action_callback_method_name = "#{controller_callback_method_name}_#{controller.action_name}"
__send__(controller_callback_method_name) if respond_to?(controller_callback_method_name, true)
__send__(action_callback_method_name) if respond_to?(action_callback_method_name, true)
end
def method_missing(method, *arguments, &block)
return unless @controller
@controller.__send__(method, *arguments, &block)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment