【问题标题】:ActiveResource models + SweepersActiveResource 模型 + 清扫器
【发布时间】:2011-12-09 16:26:55
【问题描述】:

我刚刚开始使用 ActiveResource,并决定缓存模型的一些位,这样我就不会不停地访问 api。好的,好的。

我查看了即将过期的缓存,并决定实施清扫器(我还没有这样做)。这不起作用。

AR 模型:

class Myresource < ActiveResource::Base
  extend ActiveModel::Callbacks
  define_model_callbacks :update

  "stuff"

  def current
    Rails.cache.fetch("/key/#{self.id}", :expires_in => 5.minutes) do
      Myresource.find(ID)
    end 
  end

end

清道夫:

class MyresourceSweeper < ActionController::Caching::Sweeper
  observe Myresource

  def after_update(myresource)
    expire_cache_for_myresource
  end

private
  def expire_cache_for_myresource
    Rails.cache.delete '/key/myresource.id'
  end
end

控制器:

cache_sweeper :myresource_sweeper

因此,我只使用了一点 AR、缓存和 Sweepers,在尝试了各种组合之后,我不知道该去哪里看。我可以从控制台为资源设置和过期,但在应用程序中,缓存被设置,但我所做的一切都没有触发删除。

建议?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 caching activeresource


    【解决方案1】:

    您发布的代码有错字。我有点怀疑这是你真正的问题,但对于它的价值,我认为你的意思是写你的清扫器如下:

    class MyresourceSweeper < ActionController::Caching::Sweeper
      observe Myresource
    
      def after_update(myresource)
        expire_cache_for_myresource(myresource)
      end
    
      private
      def expire_cache_for_myresource(myresource)
        Rails.cache.delete "/key/#{myresource.id}"
      end
    end
    

    例如在您发布的原始代码中,您没有将资源传递给 expire_cache_for_my_resource 方法,因此一遍又一遍地使相同的静态密钥过期。

    【讨论】:

    • 是的,错别字是将实际代码翻译成某种东西的一部分。它比这更复杂一些,但是我没有正确传递 myresource (当我仍在将钩子放入模型中时,我已经删除了一部分,我当时不知道我需要, 但无论如何)。当我把它放在一边并回到它时就发现了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2013-09-04
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多