How to cache the action of rails with url parameters and be able to cancel it

I serve the default image for users at URL / url / username / picture (very similar to facebook). An action requires several capture parameters to indicate the size and style of the image. Here is an example:

/ John / image d [] = 50 &? D [] = 50 & s = square

This will return a default 50px x 50px johns image cropped as a square.

Pressing the entire rake for each image request is clearly inefficient. I would like to cache image versions. It seems possible with a bit of a solution to this question .

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

However, I need to find a way to clear the cache for all versions of the images when the user changes the default image. Basically, when john changes the default image, I would like for me to be able to clear using a regular expression like the one below, so that all thumbnails are restored to the default with the new default image:

clear cache / john / picture *

How to do it on rails?

+4
source share
3 answers

I might not understand your question, but I think you need a sweeper. http://guides.rubyonrails.org/caching_with_rails.html#sweepers

+1
source

next to your cache_index , you can assign the cache_sweeper class in your controller.

 # assign the cache_sweeper caches_action :my_action, :cache_path => Proc.new { |c| c.params } cache_sweeper :picture_sweeper 

then along with your controllers add a new class

 # 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 

Caching Documents

0
source

Checkout https://github.com/pennymac/action_param_caching for a simpler version of this.

0
source

Source: https://habr.com/ru/post/1379666/


All Articles