我有一个基于JSON
和XML
的API需要进行页面缓存。我已经在API上设置了路由,将格式作为URL的一部分包括在内,这样像这样的URL就可以工作:
http://example.com/foo/1/bar/2/xml
http://example.com/foo/1/bar/2/json
我看到的问题是,在服务器的
public
文件夹中,文件被保存为xml.xml
和json.json
,这会导致下次访问URL时缓存未命中。有没有办法:
1.关闭自动生成扩展名的功能,使其完全不带扩展名?(例如:
RAILS_ROOT/public/foo/1/bar/2/json
)2.强制所有调用的扩展名都是
.html
。(例如:RAILS_ROOT/public/foo/1/bar/2/json.html
)任何一种方法都会导致我的服务器返回缓存文件而不是未命中。我该怎么做?
编辑: 有人要求相关路由:
scope '(foo/:foo_id)', :foo_id => /\d+/ do
get '/bar/:bar_id/:format' => 'bars#show', :bar_id => /\d+/, :format => /json|xml|html/
end
解决方案:当我在寻找一种官方方法来使用内置的页面缓存支持时,最终我采用了一个过滤器和自己的页面缓存方法,正如Anton所建议的那样。
# application_controller.rb
def cache_api_page
if REDACTEDServer::Application.config.action_controller.perform_caching
self.class.cache_page(response.body, request.path, '')
puts "CACHED PATH: #{request.path}"
end
end
# bar_controller.rb
after_filter :cache_api_page, :only => [ :show, :index ]