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

**URL:** <https://www.ruby-forum.com/t/xml-builder-cache-with-a-slight-problem-on-initial-load/109878>\
**Category:** Rails\
**Created:** [July 19, 2007, 9:20pm UTC](https://www.ruby-forum.com/t/xml-builder-cache-with-a-slight-problem-on-initial-load/109878 "2007-07-19T21:20:43Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![jtarchie](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/9de053/32.png) [@jtarchie](https://www.ruby-forum.com/u/jtarchie)\
**Post date:** [July 19, 2007, 9:20pm UTC](https://www.ruby-forum.com/t/xml-builder-cache-with-a-slight-problem-on-initial-load/109878/1 "2007-07-19T21:20:43Z")

</div>

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.
