Sha256: 07562321721a86480f574e610a254d298c62e855635b9477c4d79dc23b5ec1a8

Contents?: true

Size: 1.65 KB

Versions: 1

Compression:

Stored size: 1.65 KB

Contents

#require 'active_support'

module Trigga
  module Cache
    module FileCache
      
      module_function
      
      
      @cache_dir =  "#{defined?(RAILS_ROOT) ? RAILS_ROOT : ''}/tmp/cache"
      @timeout_seconds = 3600 # <- default timeout is 1hr
      
      def cache_dir
        @cache_dir 
      end
      
      def cache_dir=(dir)
        @cache_dir=dir
      end
      
      def timeout_seconds
        @timeout_seconds
      end
      
      def timeout_seconds=(secs)
        @timeout_seconds = secs
      end
      
      def with_cache( opts={}, &block )
        begin
          if is_in_cache?(opts) && !expired?(opts)
            get(opts)
          else
            delete(opts)
            result = block.call
            put( opts, result )
            result
          end
        end
      end
      
      def get(opts)
        File.open( file_path(opts), 'r' ){ |f| f.read }
      end
      
      def put(opts, content)
        File.open( file_path(opts), 'w' ){ |f| f.write(content) }
      end
      
      def delete(opts)
        File.delete(file_path(opts)) if is_in_cache?(opts)
      end
      
      def is_in_cache?( opts={} )        
        File.exists?( file_path(opts) )
      end
      
      def expired?( opts={} )    
        opts[:timeout_seconds] ||= self.timeout_seconds
        Time.now - File.mtime(file_path(opts)) > opts[:timeout_seconds]
      end
      
      def file_path( opts )
        raise ArgumentError.new(":cache_key is required") unless opts[:cache_key]
        
        opts[:cache_dir] ||= self.cache_dir
        
        File.expand_path( File.join(opts[:cache_dir], opts[:cache_key]) )
      end
    end
  end
end

    

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
itrigga-file_cache-0.1.0 lib/itrigga/cache/itrigga-file_cache.rb