= cache_flow
Drop-dead simple XML fragment caching in Builder templates!
How is it that RESTful web services riding Rails are such a big thing and there doesn't seem to be one definitive, up-to-date reference as to how to cache the XML output? Well cache_flow was built to solve that very problem... and _surprisingly_ easily!
You may be saying to yourself, "Yes, Rails web services are cool, but only if you're using ActiveRecord::Base#to_xml." Agree to disagree. The to_xml approach is just fine, but it seems like scaffolding. I believe there are some serious advantages to building your XML in the view:
1. It's the view! You wouldn't build your HTML in the model, so why your XML? (See http://bit.ly/rails-models-are-views)
2. Flexibility. Name your XML nodes anything you want. You're not tied down to your column (or even method) names.
3. And now... caching! Cache your XML output like you would your ERB views.
== Installation
In environment.rb:
Rails::Initializer.run do |config|
config.gem 'cache_flow'
end
At your application root, run:
$ sudo rake gems:install
== Example
To cache a chunk of XML, use the one method that cache_flow adds to your Builder instance, aptly named cache!:
xml.users, :type => 'array' do
@users.each do |user|
xml.cache!(user) do
xml.user do
xml.first_name user.first_name
xml.last_name user.last_name
end
end
end
end
It's that easy! The cache! method takes the same arguments as the cache method we all know and love from our ERB views. So in the example above, user.cache_key will be automatically used as the cache key. You get all the same goodies as Rails' built-in fragment caching.
== How It Works
Behind the scenes, cache_flow is using the same mechanism that's used for caching ERB fragments, only using XmlMarkup#target! as its buffer rather than ActionView::Base#output_buffer. I'd like to take more credit, but it really _is_ that simple.
== To-Do
* Write tests. Any takers? I'm not very familiar with testing the view layer.