Class: Concrete::FileCacheMap

Inherits:
Object
  • Object
show all
Defined in:
lib/concrete/file_cache_map.rb

Overview

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.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cacheDir, postfix) ⇒ FileCacheMap

cacheDir is the name of the subfolder where cache files are created postfix is an extension appended to the original file name in order to create the name of the cache file



20
21
22
23
# File 'lib/concrete/file_cache_map.rb', line 20

def initialize(cacheDir, postfix)
  @postfix = postfix
  @cacheDir = cacheDir
end

Instance Attribute Details

#versionInfoObject

optional program version info to be associated with the cache files if the program version changes, cached data will also be invalid



15
16
17
# File 'lib/concrete/file_cache_map.rb', line 15

def versionInfo
  @versionInfo
end

Instance Method Details

#cleanUnused(rootPath, keyPaths) ⇒ Object

remove cache files which are not associated with any file in keyPaths will only remove files within rootPath



60
61
62
63
64
65
66
67
# File 'lib/concrete/file_cache_map.rb', line 60

def cleanUnused(rootPath, keyPaths)
  raise "key paths must be within root path" unless keyPaths.all?{|p| p.index(rootPath) == 0}
  usedFiles = keyPaths.collect{|p| cacheFile(p)}
  files = Dir[rootPath+"/**/"+@cacheDir+"/*"+@postfix] 
  files.each do |f|
    FileUtils.rm(f) unless usedFiles.include?(f)
  end
end

#loadData(keyPath) ⇒ Object

load data associated with file keyPath returns :invalid in case either the associated file or the cache file has changed



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/concrete/file_cache_map.rb', line 27

def loadData(keyPath)
  cf = cacheFile(keyPath)
  return :invalid unless File.exist?(cf)
  result = nil
  File.open(cf, "rb") do |f|
    checksum = f.read(41)[0..39]
    data = f.read
    if calcSha1(data) == checksum
      if calcSha1(keyData(keyPath)) == data[0..39]
        result = data[41..-1]
      else
        result = :invalid
      end
    else
      result = :invalid
    end
  end 
  result
end

#storeData(keyPath, valueData) ⇒ Object

store data valueData associated with file keyPath



48
49
50
51
52
53
54
55
56
# File 'lib/concrete/file_cache_map.rb', line 48

def storeData(keyPath, valueData)
  data = calcSha1(keyData(keyPath)) + "\n" + valueData
  data = calcSha1(data) + "\n" + data
  cf = cacheFile(keyPath)
  FileUtils.mkdir(File.dirname(cf)) unless File.exist?(File.dirname(cf))
  File.open(cf, "wb") do |f|
    f.write(data)
  end 
end