开发者

Rails3 and Easily caching views and controllers

开发者 https://www.devze.com 2023-01-16 03:54 出处:网络
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.

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 th开发者_Go百科em.

Thanks ;)


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/


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消