3

当我们使用缓存摘要在 Rails 中缓存一个部分时,部分中的条件逻辑是如何处理的?它是否缓存了完整的模板并稍后应用条件,以便可以将正确的 json/html 提供给正确的用户?

4

1 回答 1

1

它是否缓存了完整的模板并稍后应用条件,以便可以将正确的 json/html 提供给正确的用户?

这部分问题对我来说似乎有点不清楚,所以我将根据“条件”可能是什么提供不同的选项。

首先,缓存摘要不关心基于@variables 状态的内部条件(除非在其缓存键中提到特定状态)。考虑以下示例:

# users.haml
.welcome_block
  - if @user.admin?
    %h4 Hello, admin!
  - else
    %h4 Hello, user!

如果您使用 将缓存应用于整个页面cache ['users_haml'],则缓存将仅生成一次(对于具有任何角色的第一个用户)。稍后访问此页面的任何用户都会看到与h4显示给第一个用户的问候语相同的问候语。这里的原因是,digest对于 string users_haml,证明为cache方法,无论在任何情况下都是相同的。

另一方面,cache @user会提供稍微不同的行为。每个打开users.haml页面的用户都会根据他/她的角色看到适当的问候语。这种行为的原因是digest所有类型的对象都不同User,因此会cache_digests为 N 个用户生成 N 个缓存页面。

想到的最后一种条件是基于条件部分渲染的条件,例如:

# users.haml
- cache [@user.month_of_birth]
  - if @user.month_of_birth == 'October'
    = render 'partial_one'
  - else
    = render 'partial_two'

So, this one renders correct cached page for users with different months of birth. But what should happen if I change the contents of partial_one? How does cache_digests understand that cache should be invalidated for those who were born in october (based on the conditional statement)?

The answer here is that it doesn't know that at all. The only thing it knows is that users.haml depends on both partial_one and partial_two, so changes to either of these inner partials gonna invalidate ALL the users.haml page caches regardless of users' month of birth.

于 2014-10-01T13:22:34.033 回答