ruby-on-railscachingsweeper

Can Rails sweepers work across different controllers?


I have action caching working on my Sites index, and set up a SiteSweeper that works fine:

# app/controllers/admin/sites_controller.rb
class Admin::SitesController < Admin::BaseController
  cache_sweeper :site_sweeper, :only => [:create, :update, :destroy]
  caches_action :index, :cache_path => '/admin/sites'
  ...

# app/sweepers/site_sweeper.rb
class SiteSweeper < ActionController::Caching::Sweeper
  observe Site

  def after_save(site)
    expire_cache(site)
  end

  def after_destroy(site)
    expire_cache(site)
  end

  def expire_cache(site)
    expire_action '/admin/sites'
  end
end

But I also want to expire /admin/sites whenever any Publishers are saved or destroyed. Is it possible to have a PublisherSweeper expire the Sites index with something like this?

# app/sweepers/publisher_sweeper.rb
class PublisherSweeper < ActionController::Caching::Sweeper
  observe Publisher

  def after_save(publisher)
    expire_cache(publisher)
  end

  def after_destroy(publisher)
    expire_cache(publisher)
  end

  def expire_cache(publisher)
    expire_action '/admin/sites'
  end
end

I know I can just call expire_action '/admin/sites' within the various Publisher actions. I'm just wondering if sweepers have this capability (to keep my controllers a bit cleaner).


Solution

  • One sweeper can observe many Models, and any controller can have multiple sweepers.

    I think you should change your logic to use something like that:

    class SiteSweeper < ActionController::Caching::Sweeper
      observe Site, Publisher
      (…)
    end
    

    On PublishersController

      cache_sweeper :site_sweeper, :admin_sweeper
    

    So you don't repeat the logic of cleaning the /admin/site. Call it AdminSweeper, so when something goes wrong you know the only one place that expired the "/admin/sites" action.