Best way to combine fragment and object caching for memcached and Rails

前端 未结 5 633
故里飘歌
故里飘歌 2021-01-31 12:11

Lets say you have a fragment of the page which displays the most recent posts, and you expire it in 30 minutes. I\'m using Rails here.

<% cache(\"recent_posts         


        
5条回答
  •  孤街浪徒
    2021-01-31 13:06

    You may also want to look into

    Fragment Cache Docs

    Which allow you to do this:

    <% cache("recent_posts", :expires_in => 30.minutes) do %>
      ...
    <% end %>
    

    Controller

    unless fragment_exist?("recent_posts")
      @posts = Post.find(:all, :limit=>20, :order=>"updated_at DESC")
    end
    

    Although I admit the issue of DRY still rears its head needing the name of the key in two places. I usually do this similar to how Lars suggested but it really depends on taste. Other developers I know stick with checking fragment exist.

    Update:

    If you look at the fragment docs, you can see how it gets rid of needing the view prefix:

    # File vendor/rails/actionpack/lib/action_controller/caching/fragments.rb, line 33
    def fragment_cache_key(key)
      ActiveSupport::Cache.expand_cache_key(key.is_a?(Hash) ? url_for(key).split("://").last : key, :views)
    end
    

提交回复
热议问题