cache_concern.rb 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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.each_with_object({}) { |item, h| h[item.id] = item }
  32. uncached.each_value do |item|
  33. Rails.cache.write(item, item)
  34. end
  35. end
  36. raw.map { |item| cached_keys_with_value[item.id] || uncached[item.id] }.compact
  37. end
  38. end