【发布时间】:2016-05-04 19:06:07
【问题描述】:
对于 JSON API,我使用fresh_when,就像这样(简化):
class BalancesController < ApplicationController
def mine
fresh_when(current_user.balance)
end
end
这适用于 ETags (If-None-Match) 和 updated_at (If-Modified-Since) 就好了。
但是,我想使不同语言的缓存失效。简化:
class BalancesController < ApplicationController
before_action :set_locale
def mine
fresh_when(current_user.balance)
end
private
def set_locale
@locale = locale_from_headers
end
end
locale_from_headers 是一个更复杂的库,但对于这个例子来说,"Accept-Language: nl" 或 "Accept-Language: en" 将导致 @locale 成为 :nl 或 :en 就足够了。
我想在 etag 和 if-modified 中使用它。这样当请求不同的语言时,fresh_when 不会返回缓存的响应。像这样:
-
get /balances/mine, {}, { "Accept-Language" => "en" }#=> 响应 200 OK -
get /balances/mine, {}, { "Accept-Language" => "en", "If-None-Match" => previous_response.headers["ETag"] }#=> 响应 304 未修改 -
get /balances/mine, {}, { "Accept-Language" => "nl", "If-None-Match" => previous_response.headers["ETag"] }#=> 响应 200 OK -
get /balances/mine, {}, { "Accept-Language" => "nl", "If-None-Match" => previous_response.headers["ETag"] }#=> 响应 304 未修改
因此,只有当语言环境与缓存的版本匹配时,响应才会被缓存并返回为 304。
使用 cache() 块,在 Rails 中使用片段缓存,adding a locale is simple。
如何使用fresh_when 方法实现相同的效果?
【问题讨论】:
标签: ruby-on-rails caching etag