5

Is there any way to leverage the new caching strategy in Rails 4 (cache_digests) for XML?

I suppose I could use xml.erb views, but I prefer xml.builder views for their terseness.

Is there any way to use cache_digests in this way?

4

1 回答 1

7

To use fragment caching and Rails 4 cache_digests in XML Builder files, just use the cache method, which works exactly like in other templates. Here is an example of russian doll caching of a (simplified) blog RSS feed:

# feed.xml.builder

xml.instruct! :xml, version: "1.0"
xml.rss version: "2.0", 'xmlns:atom': 'http://www.w3.org/2005/Atom' do
  xml.channel do
    xml.title "My Blog"

    cache "articles/feed-#{@articles.count}-#{@articles.maximum(:updated_at).try(:to_i)}" do
      @articles.each do |article|
        cache article do
          xml.item do
            xml.title article.title
            xml.description article.body
          end
        end
      end
    end
  end
end
于 2015-04-13T04:33:28.070 回答