Xml builder cache (with a slight problem on initial load)

Let me give you the background. I am using rxml for a lot of my views
for a rails project. I also noticed that there is a lot of the XML
being dynamically generated on data that doesn’t change that often. I
worked on trying to cache the xml fragment that I needed but came to
the quick realization that cache only handle ERB/RHTML files. Needless
to say, I have spent some time creating an XML fragment cache for rxml
files.

A slight problem with it though.

Let me present the code. It is derived directly from the cache and
cache_erb_fragment routines.

module ActionView
module Helpers
module CacheHelper
def cache_xml(xml, name ={}, &block)
@controller.cache_xml_fragment(block, xml, name)
end
end
end
end

module ActionController
module Caching
module Fragments
def cache_xml_fragment(block, xml, name = {}, options = nil)
unless perform_caching then block.call; return end
if cache = read_fragment(name, options)
xml << cache
else
buffer = ‘’
xml_builder = Builder::XmlMarkup.new(:target=>buffer)
block.call(xml_builder)
write_fragment(name,buffer, options)
xml << buffer
end
end
end
end
end
To use the cache_xml you pass the current xml object and the ‘name’ of
the fragment. This is a simplified example (w/o the dynamic loading of
data) but the problem that occurs still happens.
directors = [‘George Lukas’,‘Steven Speilberg’,‘Michael Bay’]
xml.instruct!
xml.directors do
directors.each do |name|
cache_xml(xml,:action=>‘director’,:name=>name) do
xml.director :name=>name
end
end
end

On the initial load of the RXML file I can indeed see that each cache
fragment is being created with a ‘Cached fragment’ line on my dev
log.

This is the rendering of the initial XML:



This is the expected output





On a second request of the XML, everything renders correctly, but I am
trying to figure out why it doesn’t happen on the initial request.

I believe the problem occurs with the block call within
cache_xml_fragment, but I have no idea what is causing the problem.

If you have any questions please feel free to ask.