Sha256: 2dc73cc58a1290ff7f032ca3162a616e5703a7b247ae2e0fea783bc72021cb53

Contents?: true

Size: 1.65 KB

Versions: 1

Compression:

Stored size: 1.65 KB

Contents

#require 'active_support'

module Itrigga
  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].to_i
      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.2.1 lib/itrigga/cache/itrigga-file_cache.rb