Search code examples
ruby-on-railsruby-on-rails-3action-caching

Expire action cache with custom cache_path


I'm having some problem expiring an action cache in my application.

Here is my controller:

class ToplistsController < ApplicationController
  caches_action :songs, cache_path: :custom_cache_path.to_proc

  def custom_cache_path
    "#{params[:when]}-#{params[:what]}-#{params[:controller]}-#{params[:action]}"
  end

  def songs
    # ...
  end  
end

I somehow need to be able to reset the custom cache path, but I can't figure out how.

I've already tried using this technique, without success. It looks like Dalli, which is my cache engine, doesn't support regexp matcher.

I'm getting this error when trying to use this code:

expire_fragment(/songs/)

ActiveSupport::Cache::DalliStore does not support delete_matched

I've tried to use this line of code, for debugging, but it's being ignored.

before_filter only: [:songs] 
  expire_fragment(custom_cache_path)
end

I'm using Rails 3.1.0.rc6, Dalli 1.0.5 and Ruby 1.9.2.


Solution

  • The before_filter block was ignored duo to the action cache.
    The solution is to use a fragment cache instead.

    # Controller
    class ToplistsController < ApplicationController
      helper_method :custom_cache_path
    
      before_filter only: [:songs]
        if params[:reset_cache]
          expire_fragment(custom_cache_path)
        end
      end
    
      def custom_cache_path
        "#{params[:when]}-#{params[:what]}-#{params[:controller]}-#{params[:action]}"
      end
    
      def songs
        # ...
      end  
    end
    
    # View
    
    <%= cache custom_cache_path do %>
      Content that should be cached
    <% end %>