Sha256: 0967d7a9d98e3d6366f6ea0a8abc93684035b8b5724de8afbe08c9edbfec4b9e

Contents?: true

Size: 1.52 KB

Versions: 3

Compression:

Stored size: 1.52 KB

Contents

# http://stackoverflow.com/questions/4217968/a-problem-about-singleton-in-ruby

#
#  To implement a backend it needs to respond to:
#  - self.setup!
#  - get
#  - set
#  - delete
# 


require 'singleton'

module Itrigga
  module Cache
    
    class Filecache
      include Singleton 
      
      attr_accessor :cache_dir, :timeout, :enabled
      
      def self.setup!(opts = {})
        instance.cache_dir =  opts[:cache_dir] || "#{defined?(RAILS_ROOT) ? RAILS_ROOT : ''}/tmp/cache"
        instance.timeout = opts[:timeout] || 3600
        instance.enabled = true
        instance
      end
      
      def get(key, opts = {})
        if expired?(key, opts)
          delete(key, opts)
          nil
        else
          File.open( file_path(key, opts), 'r' ){ |f| f.read } if is_in_cache?(key, opts)
        end
      end
      
      def set(key, content, opts = {})
        File.open( file_path(key, opts), 'w' ){ |f| f.write(content) }
      end
      
      def delete(key, opts = {})
        File.delete( file_path(key, opts)) if is_in_cache?(key, opts)
      end
      
      def file_path(key, opts = {})
        File.expand_path(File.join(opts[:cache_dir] || cache_dir, key ))
      end
      
      def is_in_cache?(key, opts={} )        
        File.exists?( file_path(key, opts) )
      end
      
      def expired?(key, opts={} ) 
        return true unless is_in_cache?(key, opts)
        opts[:timeout] ||= timeout
        Time.now - File.mtime(file_path(key, opts)) > opts[:timeout].to_i
      end      
      
    end
    
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
itrigga-cache-1.1.0 lib/itrigga/cache/filecache.rb
itrigga-cache-0.3.0 lib/itrigga/cache/filecache.rb
itrigga-cache-0.2.1 lib/itrigga/cache/filecache.rb