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?

BiscuitBaker
  • 1,421
  • 3
  • 23
  • 37
tiekuhn
  • 15
  • 4

1 Answers1

0

before this part of code (or in your controller or presenter):

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

try this:

@minutes_to_next_run ||= usecase.minutesToNextRun

in the example above, if @minutes_to_next_run is nil, then it is set equal to usecase.minutesToNextRun. If it has a value, it uses it. If you read it symantically, it makes sense:

@minutes_to_next_run OR @minutes_to_next_run = usecase.minutesToNextRun

here is a (very) definitive answer about this

Community
  • 1
  • 1
dax
  • 10,779
  • 8
  • 51
  • 86
  • Hi, ... thanks for your fast answer...and it works :-)!!! could you tell me what the code actually changes? It just seems to call the function anyway (cause @minutes_to_next_run is not set) – tiekuhn Feb 28 '14 at 15:45
  • Hi, thanks again for the comment and link. Still the statement seems to say "if @minutes_to_next_run is not set (which it is not) assign usecase.minutesToNextRun" --> this should then still call usecase.minutesToNextRun which is the expensive call I wanted to circumvent :-) – tiekuhn Feb 28 '14 at 16:25
  • right, the difference is that the expensive call only gets called once – dax Feb 28 '14 at 20:41