Class: PieceCache::FileCacheStore

Inherits:
Merb::Cache::FileStore
  • Object
show all
Defined in:
lib/merb_piece_cache/file_cache_store.rb

Constant Summary collapse

MAX_TIMESTAMP =

Tue Jan 19 03:14:07 UTC 2038

Time.at(0x7fffffff)

Instance Method Summary collapse

Instance Method Details

#pathify(key, parameters = {}) ⇒ Object



13
14
15
16
17
# File 'lib/merb_piece_cache/file_cache_store.rb', line 13

def pathify(key, parameters = {})
  filename = super
  ctype = parameters[:content_type]
  ctype ? "#{filename}.#{ctype}" : filename
end

#read(key, parameters = {}) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/merb_piece_cache/file_cache_store.rb', line 19

def read(key, parameters = {})
  ## if cache file is not found, return nil
  fpath = pathify(key)  # or pathify(key, parameters)
  return nil unless File.exist?(fpath)
  ## if cache file is created before timestamp, return nil
  timestamp = parameters[:timestamp]
  return nil if timestamp && File.ctime(fpath) < timestamp
  ## if cache file is expired, return nil
  return nil if File.mtime(fpath) <= Time.now
  ## return cache file content
  return read_file(fpath)
end

#read_file(path) ⇒ Object



51
52
53
# File 'lib/merb_piece_cache/file_cache_store.rb', line 51

def read_file(path)
  File.open(path, 'rb') {|f| f.read() }
end

#write(key, data = nil, parameters = {}, conditions = {}) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/merb_piece_cache/file_cache_store.rb', line 34

def write(key, data = nil, parameters = {}, conditions = {})
  ## create directory for cache
  fpath = pathify(key)  # or pathify(key, parameters)
  dir = File.dirname(fpath)
  FileUtils.mkdir_p(dir) unless File.exist?(dir)
  ## write data into file
  File.unlink(fpath) if File.exist?(fpath)
  write_file(fpath, data)
  ## set mtime (which is regarded as cache expired timestamp)
  lifetime = parameters[:lifetime]
  timestamp = lifetime && lifetime > 0 ? Time.now + lifetime : MAX_TIMESTAMP
  File.utime(timestamp, timestamp, fpath)
  ## return data
  return data
end

#write_file(path, data) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/merb_piece_cache/file_cache_store.rb', line 60

def write_file(path, data)
  ## write into tempoary file and rename it to path (in order not to call flock)
  tmppath = "#{path}#{rand().to_s[1,6]}"
  begin
    File.open(tmppath, 'wb') {|f| f.write(data) }
    File.rename(tmppath, path)
  rescue => ex
    File.unlink tmppath if File.exist?(tmppath)
    File.unlink path    if File.exist?(path)
    raise ex
  end
  true
end