Module: ChunkyCache::ViewHelpers

Defined in:
lib/chunky_cache/view_helpers.rb

Instance Method Summary collapse

Instance Method Details

#cache_chunk(*context, &block) ⇒ String

Denote a cached chunk of markup. This captures the block and instead returns just a placeholder string for replacement at the end of the ‘chunky_cache` run.

Parameters:

  • context (*Object)

    one or multiple objects which respond to ‘#cache_key` or convert to strings

Returns:

  • (String)

    the placeholder key



65
66
67
68
69
70
71
72
73
# File 'lib/chunky_cache/view_helpers.rb', line 65

def cache_chunk(*context, &block)
  return block.call(*context) if memory_cache.nil? || !memory_cache[:perform_caching]

  key = context.map { |k| k.try(:cache_key) || k.to_s }.unshift(template_root_key).join(":")

  memory_cache[:key_blocks][key] = [block, context]

  return key
end

#chunky_cache(**cache_options) ⇒ ActiveSupport::SafeBuffer

Begin an exciting cache block. This has to wrap calls to ‘cache_chunk`. This will absorb the contents of the block, allowing it to discover the `cache_chunk` calls, before multi-fetching all keys and then reinserting the cached contents or blocks into the correct places in the output.

All keyword arguments are passed to the cache store, but Rails only supports ‘expires_in` for `fetch_multi` anyway.

Parameters:

  • expires_in (ActiveSupport::Duration, Integer)

    expiry time will be passed to the underlying store

Returns:

  • (ActiveSupport::SafeBuffer)


16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/chunky_cache/view_helpers.rb', line 16

def chunky_cache(**cache_options)
  # Return if the memory cache is already established, as an outer run of
  # this method is in progress already
  return capture { yield } if memory_cache.present?

  # Set up the in-memory cache for this block
  establish_memory_cache(cache_options)

  # Exit out if caching isn't enabled
  return capture { yield } unless memory_cache[:perform_caching]

  blocks = memory_cache[:key_blocks]
  output_buffer = ActiveSupport::SafeBuffer.new

  # Capture the block, storing its output in a string
  big_ol_strang = capture do
    yield
  end

  # This probably shouldn't happen
  return if big_ol_strang.nil?
  
  # Now the cache blocks are populated and the placeholders in place,
  # we multi-fetch all the keys from the cache, or call the `cache_chunk` blocks
  # for missing values.
  chunks = Rails.cache.fetch_multi(*blocks.keys, **cache_options) do |missing_key|
    capture do
      block, context = *blocks[missing_key]
      block.call(*context)
    end
  end

  chunks.each do |key, chunk|
    pre, big_ol_strang = *big_ol_strang.split(key, 2)
    output_buffer << pre.html_safe
    output_buffer << chunk
  end

  reset_memory_cache

  output_buffer
end