使用 Grape 做 API 的兄弟们如果使用 Jbuilder 来构建模板。想用 HTTP caching 的话可以考虑一下这个 Gem
https://github.com/wjp2013/grape-shaman_cache
仅在非 Rails 应用上,测试通过。
ruby
get "/v1/products" do
@products = Product.xxxxxxxx.per(params[:per_page] || 20).order(params[:order] || "id DESC")
etag(@cache_key = Digest::MD5.hexdigest([@products.map{|product| product.updated_at}, request.query_string].join))
render :rabl, :"v1/products/index", :format => "json"
end
products/index.rabl
object false
cache [:products, @cache_key]
child(:meta) do
node(:pagination){|_| pagination_hash(@products)}
node(:message){|_| @message}
end
node(:data) do
partial("v1/products/_product", :object => @products)
end
静态化:
get "/v1/global_nav" do
expires 2.weeks, :public, :must_revalidate
etag(@cache_key = [Time.now.strftime("%Y%m"), "global_nav", request.query_string].join)
# logic here
render :rabl, :"v1/global_nav", :format => :json
end