Files
openfoodnetwork/app/services/cache_service.rb
Matt-Yorkley b00fbd69ae Update Fragment Caching for Rails 4
Rails 4 introduced "automagically" modified cache keys, that included a digest in the key on any cache entry related to views. This is not what we want at all, fixed here with the `skip_digest: true` option.
2020-05-22 14:22:21 +02:00

69 lines
2.0 KiB
Ruby

# frozen_string_literal: true
class CacheService
HOME_STATS_EXPIRY = 1.day.freeze
FILTERS_EXPIRY = 30.seconds.freeze
SHOPS_EXPIRY = 15.seconds.freeze
def self.cache(cache_key, options = {})
Rails.cache.fetch cache_key.to_s, options do
yield
end
end
# Yields a cached query, expired by the most recently updated record for a given class.
# E.g: if *any* Spree::Taxon record is updated, all keys based on Spree::Taxon will auto-expire.
def self.cached_data_by_class(cache_key, cached_class)
Rails.cache.fetch "#{cache_key}-#{cached_class}-#{latest_timestamp_by_class(cached_class)}" do
yield
end
end
# Gets the :updated_at value of the most recently updated record for a given class, and returns
# it as a timestamp, eg: `1583836069`.
def self.latest_timestamp_by_class(cached_class)
cached_class.maximum(:updated_at).to_i
end
def self.home_stats(statistic)
Rails.cache.fetch("home_stats_count_#{statistic}",
expires_in: HOME_STATS_EXPIRY,
race_condition_ttl: 10) do
yield
end
end
module FragmentCaching
# Rails' caching in views is called "Fragment Caching" and uses some slightly different logic.
# Note: keys supplied here are actually prepended with "views/" under the hood.
def self.ams_all_taxons
[
"inject-all-taxons-#{CacheService.latest_timestamp_by_class(Spree::Taxon)}",
{ skip_digest: true }
]
end
def self.ams_all_properties
[
"inject-all-properties-#{CacheService.latest_timestamp_by_class(Spree::Property)}",
{ skip_digest: true }
]
end
def self.ams_shops
[
"shops/index/inject_enterprises",
{ expires_in: SHOPS_EXPIRY, skip_digest: true }
]
end
def self.ams_shop(enterprise)
[
"enterprises/shop/inject_enterprise_shopfront-#{enterprise.id}",
{ expires_in: SHOPS_EXPIRY, skip_digest: true }
]
end
end
end