Module: BackgroundCache::Helper

Defined in:
lib/background_cache/helper.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



4
5
6
# File 'lib/background_cache/helper.rb', line 4

def self.included(base)
  base.alias_method_chain :cache, :background_cache
end

Instance Method Details

#cache_with_background_cache(name = {}, options = nil, &block) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/background_cache/helper.rb', line 8

def cache_with_background_cache(name = {}, options = nil, &block)
  # http://railsapi.com/doc/rails-v2.3.8/classes/ActionView/Helpers/CacheHelper.html
  # ActionController::Caching::Fragments#fragment_for (undocumented)
  #   actionpack/lib/action_controller/caching/fragments.rb
  perform_caching =
    if controller.respond_to?(:perform_caching)
      controller.perform_caching
    else
      ActionController::Base.perform_caching
    end
  if perform_caching
    cache = controller.read_fragment(name, options)
    match = (
      BackgroundCache.active? &&
      BackgroundCache.match?(name)
    )
    if !cache || match
      pos = output_buffer.length
      block.call
      output = [
        "<!-- #{name.inspect}#{' background' if match} cached #{Time.now.strftime("%m/%d/%Y at %I:%M %p")} -->",
        output_buffer[pos..-1]
      ].join("\n")
      controller.write_fragment(name, output, options)
    else
      output_buffer.concat(cache)
    end
  else
    block.call
  end
end