collection_caching.rb 2.2 KB
Newer Older
1 2 3 4 5 6 7 8
require 'active_support/core_ext/object/try'

module ActionView
  module CollectionCaching # :nodoc:
    extend ActiveSupport::Concern

    included do
      # Fallback cache store if Action View is used without Rails.
K
karanarora 已提交
9
      # Otherwise overridden in Railtie to use Rails.cache.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
      mattr_accessor(:collection_cache) { ActiveSupport::Cache::MemoryStore.new }
    end

    private
      def cache_collection_render
        return yield unless cache_collection?

        keyed_collection = collection_by_cache_keys
        partial_cache = collection_cache.read_multi(*keyed_collection.keys)

        @collection = keyed_collection.reject { |key, _| partial_cache.key?(key) }.values
        rendered_partials = @collection.any? ? yield.dup : []

        fetch_or_cache_partial(partial_cache, order_by: keyed_collection.each_key) do
          rendered_partials.shift
        end
      end

      def cache_collection?
29 30 31 32 33 34 35 36 37 38 39 40 41 42
        @options.fetch(:cache, automatic_cache_eligible?)
      end

      def automatic_cache_eligible?
        single_template_render? && !callable_cache_key? &&
          @template.eligible_for_collection_caching?(as: @options[:as])
      end

      def single_template_render?
        @template # Template is only set when a collection renders one template.
      end

      def callable_cache_key?
        @options[:cache].respond_to?(:call)
43 44 45
      end

      def collection_by_cache_keys
46
        seed = callable_cache_key? ? @options[:cache] : ->(i) { i }
47 48 49 50 51 52 53

        @collection.each_with_object({}) do |item, hash|
          hash[expanded_cache_key(seed.call(item))] = item
        end
      end

      def expanded_cache_key(key)
54
        key = @view.fragment_cache_key(@view.cache_fragment_name(key, virtual_path: @template.virtual_path))
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
        key.frozen? ? key.dup : key # #read_multi & #write may require mutability, Dalli 2.6.0.
      end

      def fetch_or_cache_partial(cached_partials, order_by:)
        cache_options = @options[:cache_options] || @locals[:cache_options] || {}

        order_by.map do |key|
          cached_partials.fetch(key) do
            yield.tap do |rendered_partial|
              collection_cache.write(key, rendered_partial, cache_options)
            end
          end
        end
      end
  end
end