How to invoke Rails cache sweeper from a rake task?

I set up a Rails cache sweeper like below:

class ArticleSweeper < ActionController::Caching::Sweeper
  observe Article

  def sweep(article)
    expire_page articles_path
    expire_page author_path(article.author)
    FileUtils.rm_rf "#{page_cache_directory}/articles/page"
  end

  alias_method :after_update, :sweep
  alias_method :after_create, :sweep
end

I connected this cache sweeper with the article controller.

The cache sweeping works as a result of controller action of create and update.

However, the main way I update my database records are through a rake task, which uses active record methods of save, update_attributes, etc on the database records.

I thought about adding a model observer class and let this class invoke the sweeper method. There're alot of comments online about how the cache sweeper should be triggered by model actions instead of controller actions.

But for my application, the rake task may add 100 records when it executes. So I don't want the cache sweeper to execute 100 times. As it won't be efficient.

I think it's better to execute it once at the end of the rake task.

So I tried adding this in my rake task:

ArticleSweeper.instance.sweep(Article.last)

I put a "debugger" statement in there and see that the sweep() method WAS being executed. However, the cache files are NOT being removed, even though the same code works when it's triggered by controller action.

So my question is: is it possible to trigger the cache sweeper method from a rake task? And if so, what can I do to make it work?

Thanks


我遇到了同样的问题,并且偶然发现了这个问题:http://www.madebymade.co.uk/blog/2013/08/cache-sweepers-invalidating-caches-from-outside-the-controller/

链接地址: http://www.djcxy.com/p/60362.html

上一篇: 如何创建包含特定文件的ant版本的EAR文件?

下一篇: 如何从rake任务调用Rails缓存清理器?