Saturday, August 29, 2009

Action Caching

Recently, I have been working with RESTful web services. I came to a caching stage where I need to cache some requests that map to my actions. The problem is that I have actions with multiple possible routes, therefore those routes should be cached differently. For example:


/people/1?display=details
/people/1?display=summary
/people/1?display=details&format=xml
/people/1?display=summary&format=json


Fortunately, there is an option inside caches_action called :cache_path. All you need to do is to pass a proc object and return the path you want to cache. It is called with the current controller instance. In this case,

caches_action :index, :show, :cache_path => Proc.new { |c|
request_url = { :controller => c.params[:controller], :action => c.params[:action] }.merge(c.request.query_parameters)
c.url_for request_url
}


There is another problem when the request is coming without format, the cache returns the result with content-type: text/html. To solve this, add a before_filter inside application controller to assign the headers['Content-type'].


def set_default_response_format
response.headers['Content-type'] = 'application/xml; charset=utf-8' if params[:format].nil?
end

No comments:

Subscribe in a Reader