Skip to content

Commit

Permalink
Make the logic easier to follow.
Browse files Browse the repository at this point in the history
  • Loading branch information
stefansundin committed Jan 25, 2021
1 parent d993d42 commit e649e9f
Showing 1 changed file with 18 additions and 12 deletions.
30 changes: 18 additions & 12 deletions lib/cache.rb
Expand Up @@ -33,7 +33,9 @@ def self.cache(cache_key, cache_duration, negative_cache_duration, &block)
negative_cache_duration_jitter = rand(10)

if File.file?(fn)
# There is cached data
stat = File.stat(fn)

if stat.size > 0
# There is cached data with contents
cached_data = File.read(fn)
Expand All @@ -42,12 +44,13 @@ def self.cache(cache_key, cache_duration, negative_cache_duration, &block)
end
else
if Time.now < stat.mtime+negative_cache_duration+negative_cache_duration_jitter
# There is a negative cache in place
# A negative cache is in place and it is still active
return nil, stat.mtime
end
end

# The cached data has expired
begin
# We have cached data that has expired, yield
data = yield(cached_data, stat)
rescue
if cached_data
Expand All @@ -59,24 +62,27 @@ def self.cache(cache_key, cache_duration, negative_cache_duration, &block)
FileUtils.touch(fn)
raise
end

if data == cached_data
# The new data is exactly the same as the previously cached data, so just update the file mtime
FileUtils.touch(fn, mtime: Time.now)
else
# Write new data
File.write(fn, data)
end
else
begin
# There is no cached data, yield
data = yield
rescue
# Trigger negative cache and re-raise the exception
FileUtils.touch(fn)
raise
end
File.write(fn, data)

return data, Time.now
end

# There is no cached data
begin
data = yield
rescue
# Trigger negative cache and re-raise the exception
FileUtils.touch(fn)
raise
end
File.write(fn, data)

return data, Time.now
end
Expand Down

0 comments on commit e649e9f

Please sign in to comment.