1

I am currently caching my web application.

So I was driving to use memcache and i was looking for an easy way to handle all that.

For exemple, i would like to cache all my contents until they are not modified.

And I can't cache all the page because some parts need to be cached apart.

So I could use a fragment_cache for the controller, and then an other into the views, and then in the model after an update delete the fragment.

But it feel heavy and I don't like this way.

If you have any ideas, i would be glad to hear them.

Thanks ;)

2 Answers 2

4

Have you looked at sweepers? I use them heavily in some of my apps and they work well and keep the caching separate from your model. Instead of clearing the cache in the model, you create a sweeper that observes for changes. You can specify when to clear the cache based on save, update, etc. Saves you from coding that stuff directly in the model. Just create a directory like app/sweepers and drop in one for each model you want to clear cache for. This specific example is for action cache, but you can probably apply something similar to your fragments.

  class WidgetSweeper < ActionController::Caching::Sweeper
      observe Widget
      def after_update(widget)
        expire_cache_for(widget)
      end

      def after_destroy(widget)
        expire_cache_for(widget)
      end

      def after_create(widget)
        expire_cache_for(widget)
      end

  private
    def expire_cache_for(widget)
      expire_action(:controller=>"widgets",:action=>"show",:id=>widget.id)
      expire_action(:controller=>"widgets",:action=>"index")
    end
  end

I did a writeup on action and fragment caching here with more details including how to cache based on conditions:
http://www.cowboycoded.com/2010/07/14/performance-exercise-1-rails-cache-cash/

1
  • Thanks for your answer. I didn't knew about sweepers. It is exactly what i was looking for. Answer validated ;)
    – Arkan
    Sep 10, 2010 at 14:39
0

You could also use the cache name to sweep your data.

For example, if you do:

<% cache "my_model_#{@model.updated_at}" do %>
stuff I render with my model
<% end %>

you automatically get you cache cleaned when the model is updated, and you get rid of using sweepers.

1
  • You don't have to do this as this is automatically done for you. So whenever you model.touch the cached fragment will invalidate.
    – fphilipe
    Apr 7, 2011 at 15:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.