如何使用url参数缓存rails操作并能够使其无效

时间:2011-11-04 15:31:18

标签: ruby-on-rails ruby-on-rails-3.1

我正在从url /:username / picture(非常像facebook)提供用户默认图片。该操作需要几个get参数来指定所需的图像尺寸和样式。这是一个例子:

/约翰/图象d [] = 50安培; d [] = 50安培; S =平方

这将返回johns默认图片,大小为50px x 50px裁剪为正方形。

为每个图片请求命中整个rails堆栈显然效率不高。我想缓存图像版本。这似乎可以通过解决方案to this so question来实现。

caches_action :my_action, :cache_path => Proc.new { |c| c.params }

但是,当用户更改其默认图片时,我需要找到一种清除所有图像版本缓存的方法。基本上当约翰改变他的默认图片时,我希望我能用类似于下面的正则表达式清除,以便使用新的默认图片重新生成所有默认缩略图:

清除缓存/约翰/图片*

我如何在rails中完成此操作?

3 个答案:

答案 0 :(得分:1)

我可能会误解你的问题,但我认为你需要清扫工具。 http://guides.rubyonrails.org/caching_with_rails.html#sweepers

答案 1 :(得分:0)

与您的cache_index一起,您可以在控制器中为cache_sweeper分配一个班级。

# assign the cache_sweeper
caches_action :my_action, :cache_path => Proc.new { |c| c.params }
cache_sweeper :picture_sweeper
然后,在您的控制器旁边添加一个新类

# class to help with sweeping up cached pictures
class PictureSweeper < ActionController::Caching::Sweeper
  observe Picture # or whatever your class is called
  # ... be sure to read on how to setup a cache sweeper
  def after_update( record )
    # you should probably check if record.is_a? Picture or whatever your class is
    self.class::sweep( record )
  end
  # note there is also after_create, after_destroy, after_save

  def self.sweep( record )
    # the cache directory is in ActionController::Base.page_cache_directory
    # use the record to help reconstruct the path to your cached pictures
    # and delete whatever you need to
  end

  # note, i showed the sweeping split out from the after_update method in case you
  # wanted to sweep after several of the events... trying to be DRY...
end

Cache Sweeping Docs

答案 2 :(得分:0)

结帐https://github.com/pennymac/action_param_caching以获取更简单的版本。