Implements a cache for storing and loading data associated with arbitrary files. The data is stored in cache files within a subfolder of the folder where the associated files exists. The cache files are protected with a checksum and loaded data will be invalid in case either the associated file are the cache file has changed.
cache_dir is the name of the subfolder where cache files are created postfix is an extension appended to the original file name for creating the name of the cache file
# File lib/rgen/util/file_cache_map.rb, line 22 def initialize(cache_dir, postfix) @postfix = postfix @cache_dir = cache_dir end
remove cache files which are not associated with any file in key_paths will only remove files within root_path
# File lib/rgen/util/file_cache_map.rb, line 64 def clean_unused(root_path, key_paths) raise "key paths must be within root path" unless key_paths.all?{|p| p.index(root_path) == 0} used_files = key_paths.collect{|p| cache_file(p)} files = Dir[root_path+"/**/"+@cache_dir+"/*"+@postfix] files.each do |f| FileUtils.rm(f) unless used_files.include?(f) end end
load data associated with file key_path returns :invalid in case either the associated file or the cache file has changed
# File lib/rgen/util/file_cache_map.rb, line 29 def load_data(key_path) cf = cache_file(key_path) return :invalid unless File.exist?(cf) result = nil File.open(cf, "rb") do |f| header = f.read(41) return :invalid unless header checksum = header[0..39] data = f.read if calc_sha1(data) == checksum if calc_sha1_keydata(key_path) == data[0..39] result = data[41..-1] else result = :invalid end else result = :invalid end end result end
store data value_data associated with file key_path
# File lib/rgen/util/file_cache_map.rb, line 52 def store_data(key_path, value_data) data = calc_sha1_keydata(key_path) + "\n" + value_data data = calc_sha1(data) + "\n" + data cf = cache_file(key_path) FileUtils.mkdir(File.dirname(cf)) rescue Errno::EEXIST File.open(cf, "wb") do |f| f.write(data) end end
Generated with the Darkfish Rdoc Generator 2.