You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.9 KiB

  1. # frozen_string_literal: true
  2. module CacheConcern
  3. extend ActiveSupport::Concern
  4. def render_with_cache(**options)
  5. raise ArgumentError, 'only JSON render calls are supported' unless options.key?(:json) || block_given?
  6. key = options.delete(:key) || [[params[:controller], params[:action]].join('/'), options[:json].respond_to?(:cache_key) ? options[:json].cache_key : nil, options[:fields].nil? ? nil : options[:fields].join(',')].compact.join(':')
  7. expires_in = options.delete(:expires_in) || 3.minutes
  8. body = Rails.cache.read(key, raw: true)
  9. if body
  10. render(options.except(:json, :serializer, :each_serializer, :adapter, :fields).merge(json: body))
  11. else
  12. if block_given?
  13. options[:json] = yield
  14. elsif options[:json].is_a?(Symbol)
  15. options[:json] = send(options[:json])
  16. end
  17. render(options)
  18. Rails.cache.write(key, response.body, expires_in: expires_in, raw: true)
  19. end
  20. end
  21. def set_cache_headers
  22. response.headers['Vary'] = public_fetch_mode? ? 'Accept' : 'Accept, Signature'
  23. end
  24. def cache_collection(raw, klass)
  25. return raw unless klass.respond_to?(:with_includes)
  26. raw = raw.cache_ids.to_a if raw.is_a?(ActiveRecord::Relation)
  27. cached_keys_with_value = Rails.cache.read_multi(*raw).transform_keys(&:id)
  28. uncached_ids = raw.map(&:id) - cached_keys_with_value.keys
  29. klass.reload_stale_associations!(cached_keys_with_value.values) if klass.respond_to?(:reload_stale_associations!)
  30. unless uncached_ids.empty?
  31. uncached = klass.where(id: uncached_ids).with_includes.index_by(&:id)
  32. uncached.each_value do |item|
  33. Rails.cache.write(item, item)
  34. end
  35. end
  36. raw.filter_map { |item| cached_keys_with_value[item.id] || uncached[item.id] }
  37. end
  38. def cache_collection_paginated_by_id(raw, klass, limit, options)
  39. cache_collection raw.cache_ids.to_a_paginated_by_id(limit, options), klass
  40. end
  41. end