class PageSweeper < ActionController::Caching::Sweeper observe Page, Slug def after_save model expire_cache model end def after_destroy model expire_cache model end private def expire_cache model case model.class.name.to_s when "Page" # only expire latest slug # in case title changes, it will trigger the expire_slug function from the observer expire_page "/#{model.slug.name}" # expire all cache if we change root page expire_dir nil if (model.parent_id.blank?) when "Slug" # expire from parent level down expire_parent_and_descendants model.name end end private # expire the parent directory and page def expire_parent_and_descendants slug expire_page parent_slug(slug) expire_dir parent_slug(slug) end # expire a whole cache directory def expire_dir dir cache_dir = ActionController::Base.page_cache_directory FileUtils.rm_rf Dir.glob("#{cache_dir}#{dir}") rescue Errno::ENOENT Rails.logger.info("Removed cache dir: #{cache_dir}#{dir}") end # why not split, pop and rejoin? def parent_slug slug if slug.sluggable_type == "Page" if slug.sluggable.root? slug else slug.sluggable.parent.slug.name end end end end