# 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