Sha256: 5483553778b1ea09af1aadd9349a08b872eacc0de64d61ad1452c74ffd81fbd8

Contents?: true

Size: 1.69 KB

Versions: 2

Compression:

Stored size: 1.69 KB

Contents

require 'fileutils'

require 'glue/configuration'
require 'glue/cache/memory'

module Nitro

# Adds support for caching.

module Caching

  # Action caching. Caches a fragment, ie a page part.
  # Use output caching for full page caching.

  module Fragments

    # The cache used to store the fragments.
    
    setting :cache, :default => Glue::MemoryCache.new, :doc => 'The cache used to store the fragments'
    
    def self.get(name, options = {})
      return self.cache.get(name, options)
    end
    
    def self.put(name, content = nil, options = {})
      self.cache.put(name, content, options)
      return content
    end
    
    private

    # Helper method to cache a fragment. 
    #
    # === Example
    #
    # ...
    # <h1>Article list</h1>
    #
    # <?r cache(:my_cache_key) do ?>
    #   <ul>
    #     <li each="a in Article.all">#{a.title}</li>
    #   </ul>
    # <?r end ?>
    # ...

    def cache(name = nil, options = {}, &block)
      name = @action_name unless name  
      cache_fragment(block, "#{name}#{options}", options)
    end

    # Internal method, prefer to use cache instead.
    
    def cache_fragment(block, name, options = {})
      unless caching_enabled?
        block.call
        return
      end

      if fragment = Fragments.get(name, options)
        @out << fragment
      else
        pos = @out.length        
        block.call
        Fragments.put(name, @out[pos..-1], options)
      end
    end

    # Expire a cached fragment.
    #--
    # gmosx: If you modify the code here, don't forget to modify
    # the same method on the sweeper.
    #++
    
    def expire_fragment(name, options = {})
      Fragments.cache.delete(name, options)
    end
  end
  
end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
nitro-0.41.0 lib/nitro/caching/fragments.rb
nitro-0.40.0 lib/nitro/caching/fragments.rb