Class: Ramaze::FileCache

Inherits:
Object show all
Defined in:
lib/ramaze/cache/file.rb

Overview

Persist cache contents to the filesystem. By default this will create a ‘/cache` directory in your APPDIR

Usage for sessions only:

Ramaze::Global::cache_alternative[:sessions] = Ramaze::FileCache

Usage for everything:

Ramaze::Global::cache = Ramaze::FileCache

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root = Ramaze::Global.root, subdir = 'cache') ⇒ FileCache

Returns a new instance of FileCache.



17
18
19
20
21
22
23
# File 'lib/ramaze/cache/file.rb', line 17

def initialize(root = Ramaze::Global.root, subdir = 'cache')
  @root, @subdir = root, subdir
  @host = Socket.gethostname
  @pid = $$

  FileUtils.mkdir_p(dir)
end

Instance Attribute Details

#hostObject (readonly)

Returns the value of attribute host.



15
16
17
# File 'lib/ramaze/cache/file.rb', line 15

def host
  @host
end

#pidObject (readonly)

Returns the value of attribute pid.



15
16
17
# File 'lib/ramaze/cache/file.rb', line 15

def pid
  @pid
end

#rootObject

Returns the value of attribute root.



14
15
16
# File 'lib/ramaze/cache/file.rb', line 14

def root
  @root
end

#subdirObject

Returns the value of attribute subdir.



14
15
16
# File 'lib/ramaze/cache/file.rb', line 14

def subdir
  @subdir
end

Instance Method Details

#[](key) ⇒ Object



29
30
31
32
33
# File 'lib/ramaze/cache/file.rb', line 29

def [](key)
  Marshal.load(File.read(dir(key.to_s, 'data')))
rescue
  nil
end

#[]=(key, value) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/ramaze/cache/file.rb', line 35

def []=(key, value)
  key = key.to_s
  tmp_name = dir(key, "data.#{host}.#{pid}")
  key_name = dir(key, 'data')
  dir_name = dir(key)

  data = Marshal.dump(value)

  FileUtils.rm_rf(dir_name)
  FileUtils.mkdir_p(dir_name)

  File.open(tmp_name, 'w'){|fd| fd.write(data) }

  FileUtils.mv(tmp_name, key_name)

  return value
end

#clearObject



63
64
65
# File 'lib/ramaze/cache/file.rb', line 63

def clear
  Dir[dir('*')].each{|entry| FileUtils.rm_rf(entry) }
end

#delete(*keys) ⇒ Object



57
58
59
60
61
# File 'lib/ramaze/cache/file.rb', line 57

def delete(*keys)
  keys.map do |key|
    FileUtils.rm_rf(dir(key.to_s))
  end
end

#dir(*further) ⇒ Object



25
26
27
# File 'lib/ramaze/cache/file.rb', line 25

def dir(*further)
  File.join(root, subdir, *further)
end

#to_symObject



67
68
69
# File 'lib/ramaze/cache/file.rb', line 67

def to_sym
  name.split('::').last.to_sym
end

#values_at(*keys) ⇒ Object



53
54
55
# File 'lib/ramaze/cache/file.rb', line 53

def values_at(*keys)
  keys.map{|key| self[key] }
end