Sha256: d739fbd42264d3e99f1d1c6dced2f9db0c0b692e1db8c7d21f06d2bdf77a2caa

Contents?: true

Size: 1.92 KB

Versions: 2

Compression:

Stored size: 1.92 KB

Contents

require 'fileutils'

module Nitro

# Adds support for caching.

module Caching

  # Output caching.

  module Output

    def self.included(base) # :nodoc: 
      super
      base.extend(ClassMethods)
      base.module_eval do
        cattr_accessor :output_cache_root, 'public'
      end
    end

    module ClassMethods

      def do_cache_output(path, content)
        filepath = output_cache_path(path)
        FileUtils.makedirs(File.dirname(filepath))
        File.open(filepath, 'w+') { |f| f.write(content) }
        Logger.debug "Cached page '#{filepath}'" if $DBG
      end

      # Enable output caching for the given actions.

      def cache_output(*actions)
        return unless caching_enabled?

        str = actions.collect { |a| ":#{a}" }.join(', ')

        module_eval %{
          after "do_cache_output", :on => [ #{str} ]
        }
      end

      private

      def output_cache_path(path)
        filename = ((path.empty? || path == '/') ? 'index.html' : path.dup)
#        filename.gsub!(/\/$/, '')
        filename << '/index.html' unless (filename.split('/').last || filename).include? '.'
        return output_cache_root + '/' + filename                     
      end
      
    end

    private

    def do_cache_output
      if caching_enabled? and caching_allowed?
        self.class.do_cache_output(@request.uri, @out)
      end
    end
    
    #--
    # If you change this method, don't forget the CacheSweeper
    # expire method.
    #++

    def expire_output(name)
      begin
        Logger.debug "Expirinig cache file '#{context.dispatcher.public_root}/#{name}'" if $DBG
        FileUtils.rm_rf("#{context.dispatcher.public_root}/#{name}")
      rescue Object
        # gmosx: is this the right thing to do?
      end
    end
    alias_method :delete_output, :expire_output
    
    def caching_allowed?
      not (@request.post? or @request.uri =~ /\?/)
    end

  end

end

end

# * George Moschovitis  <gm@navel.gr>

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
nitro-0.26.0 lib/nitro/caching/output.rb
nitro-0.27.0 lib/nitro/caching/output.rb