Class: ReactOnRailsPro::StreamCache::CachingComponent

Inherits:
Object
  • Object
show all
Defined in:
lib/react_on_rails_pro/stream_cache.rb

Instance Method Summary collapse

Constructor Details

#initialize(upstream_stream, cache_key, cache_options) ⇒ CachingComponent

Returns a new instance of CachingComponent.



57
58
59
60
61
# File 'lib/react_on_rails_pro/stream_cache.rb', line 57

def initialize(upstream_stream, cache_key, cache_options)
  @upstream_stream = upstream_stream
  @cache_key = cache_key
  @cache_options = cache_options
end

Instance Method Details

#each_chunk(&block) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/react_on_rails_pro/stream_cache.rb', line 63

def each_chunk(&block)
  return enum_for(:each_chunk) unless block

  buffered_chunks = []
  @upstream_stream.each_chunk do |chunk|
    # Snapshot the chunk before handing it downstream. A downstream consumer
    # receives the same object we buffer here, and this buffered array is
    # persisted to Rails.cache after the stream completes. If a consumer
    # mutates its chunk (e.g. deleting a key while framing), an un-duped
    # buffer would persist that mutation and serve a corrupted cache entry.
    # A shallow dup keeps the cached copy intact regardless of the consumer.
    # See https://github.com/shakacode/react_on_rails/issues/4550.
    buffered_chunks << chunk.dup
    yield(chunk)
  end
  Rails.cache.write(@cache_key, buffered_chunks, @cache_options || {})
end