Skip to content
Snippets Groups Projects
caching_helper.rb 907 B
# frozen_string_literal: true

module CachingHelper
  DEFAULT_EXPIRY = 1.day

  def kit_cache_chunky(expires_in: DEFAULT_EXPIRY)
    @key_blocks ||= {}
    blocks = @key_blocks[template_root_key] = {}

    big_ol_strang = capture do
      yield
    end

    chunks = Rails.cache.fetch_multi(*blocks.keys, expires_in: expires_in) do |missing_key|
      puts "Cache miss: #{missing_key}"

      capture do
        blocks[missing_key].call
      end
    end

    chunks.each do |key, chunk|
      puts "Rendering chunk: #{key}"
      big_ol_strang.gsub!(key, (chunk || ""))
    end

    big_ol_strang.html_safe
  end

  def cache_chunk(*keys, &block)
    key = keys.map! { |k| k.try(:cache_key) || k.to_s }.unshift(template_root_key).join(":")

    @key_blocks[template_root_key][key] = block

    return key
  end

  private

  def template_root_key
    digest_path_from_template(@current_template)
  end
end