1

Does anyone know why rails seems to recalculate the value of "expires_in" each time a cached fragment is read?

EXAMPLE

cache("usecase_#{usecase.id}", :expires_in => "#{usecase.minutesToNextRun}".to_i.minutes) do
    some code
end

If I check the logs I see that the usecase.minutesToNextRun method is called each time the cache fragment is read (which is quite expensive and slows down the app).

THEORY

Normally I'd expect rails to just calculate the :expires_in value once and then just compare this value (e.g. 5 minutes) to the current time (in pseudocode).

if time_the_fragment_was_stored + expires_in > now
    do nothing
else
    re-render fragment
end

QUESTION

Does anyone have any hint/idea how I can prevent rails from recalculating the expiry time each time the fragment is read?

4

1 回答 1

0

在这部分代码之前(或在您的控制器或演示者中):

cache("usecase_#{usecase.id}", :expires_in => "#{usecase.minutesToNextRun}".to_i.minutes) do
  some code
end

尝试这个:

@minutes_to_next_run ||= usecase.minutesToNextRun

在上面的例子中,如果@minutes_to_next_runnil,那么它被设置为等于usecase.minutesToNextRun。如果它有一个值,它会使用它。如果您以语义方式阅读它,那是有道理的:

@minutes_to_next_run 或 @minutes_to_next_run = usecase.minutesToNextRun

是一个(非常)明确的答案

于 2014-02-28T15:12:59.990 回答