con*_*are 6 format caching ruby-on-rails ruby-on-rails-3
我有一个JSON和XML需要进行页面缓存基于API.我在api上设置了我的路由,将格式作为URL的一部分包含在内,这样URL就像这样工作:
http://example.com/foo/1/bar/2/xml
http://example.com/foo/1/bar/2/json
Run Code Online (Sandbox Code Playgroud)
我看到的问题是,在服务器的public文件夹中,文件被保存为xml.xml和json.json,这导致下次访问URL时缓存未命中.
有没有办法:
RAILS_ROOT/public/foo/1/bar/2/json).html适用于每个呼叫.(EX: 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
Run Code Online (Sandbox Code Playgroud)
解决方案:
虽然我正在寻找一种使用内置页面缓存支持来实现这一目标的官方方法,但我最终只使用了后过滤器和我自己的页面缓存方法,如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 ]
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
class FooController < ApplicationController
after_filter(:only => :show, :if => Proc.new { |c| c.request.format.json? }) do |controller|
controller.class.cache_page(controller.response.body, controller.request.path, '.html')
end
end
Run Code Online (Sandbox Code Playgroud)
当访问http://example.com/foo/1/bar/2/json时,它将写入页面到缓存(RAILS_ROOT/public/foo/1/bar/2/json.html)
如果你得到http://example.com/foo/1/bar/2/json,你会收到RAILS_ROOT/public/foo/1/bar/2/json.html,但是你的http服务器(Apache?)应该了解该文件的内容类型。
否则内容类型将设置为“text/html”
更新
给你.htaccess
<FilesMatch "\/json$">
<IfModule mod_headers.c>
Header set Content-Type "text/json"
</IfModule>
</FilesMatch>
<FilesMatch "\/xml$">
<IfModule mod_headers.c>
Header set Content-Type "text/xml"
</IfModule>
</FilesMatch>
Run Code Online (Sandbox Code Playgroud)