Skip to content

Instantly share code, notes, and snippets.

@fbernier
Forked from asavartsov/sweeping.rb
Created January 18, 2013 14:49
Show Gist options
  • Save fbernier/4565036 to your computer and use it in GitHub Desktop.
Save fbernier/4565036 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