Sha256: afc6d278d2d614e829d5588330a894a9c632f295a0799b57dee6e9d668bc58c6

Contents?: true

Size: 1.87 KB

Versions: 2

Compression:

Stored size: 1.87 KB

Contents

require 'fileutils'

require 'glue/configuration'
require 'glue/attribute'
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 => nil, :doc => 'The cache used to store the fragments'
    
    #--
    # gmosx, FIXME: this is a hack, improve setting 
    # implementation.
    #++
    
    @@cache = Glue::MemoryCache.new
    
    def self.get(name, options = {})
      return @@cache.get(name, options)
    end
    
    def self.put(name, content = nil, options = {})
      @@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

# * George Moschovitis  <gm@navel.gr>

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
nitro-0.28.0 lib/nitro/caching/fragments.rb
nitro-0.29.0 lib/nitro/caching/fragments.rb