Class: Cachetastic::Adapters::File

Inherits:
Base
  • Object
show all
Defined in:
lib/cachetastic/adapters/file.rb

Overview

An adapter to cache objects to the file system.

This adapter supports the following configuration settings, in addition to the default settings:

configatron.cachetastic.defaults.storage_path = ::File.join(FileUtils.pwd, 'cachetastic')
configatron.cachetastic.defaults.marshal_method = :yaml

The storage_path setting defines the path to where cached objects are written to on disk.

See Cachetastic::Adapters::Base for a list of public API methods.

Instance Attribute Summary

Attributes inherited from Base

#klass

Instance Method Summary collapse

Methods inherited from Base

#debug?, #marshal, #unmarshal, #valid?

Constructor Details

#initialize(klass) ⇒ File

:nodoc:



18
19
20
21
22
23
24
# File 'lib/cachetastic/adapters/file.rb', line 18

def initialize(klass) # :nodoc:
  define_accessor(:storage_path)
  self.storage_path = ::File.join(FileUtils.pwd, 'cachetastic')
  super
  self.marshal_method = :yaml if self.marshal_method == :none
  @_file_paths = {}
end

Instance Method Details

#delete(key) ⇒ Object

set



40
41
42
43
44
45
# File 'lib/cachetastic/adapters/file.rb', line 40

def delete(key) # :nodoc:
  path = file_path(key)
  if ::File.exists?(path)
    FileUtils.rm(path)
  end
end

#expire_allObject

delete



47
48
49
50
51
# File 'lib/cachetastic/adapters/file.rb', line 47

def expire_all # :nodoc:
  @_file_paths = {}
  ::FileUtils.rm_rf(::File.join(self.storage_path, klass.name.underscore))
  return nil
end

#file_path(key) ⇒ Object

:nodoc:



57
58
59
60
61
62
63
64
65
# File 'lib/cachetastic/adapters/file.rb', line 57

def file_path(key) # :nodoc:
  path = @_file_paths[key]
  if path.nil?
    path = ::File.join(self.storage_path, klass.name.underscore, transform_key(key).scan(/(.{1,4})/).flatten, 'cache.data')
    @_file_paths[key] = path
    FileUtils.mkdir_p(::File.dirname(path))
  end
  return path
end

#get(key) ⇒ Object

:nodoc:



26
27
28
29
30
31
# File 'lib/cachetastic/adapters/file.rb', line 26

def get(key) # :nodoc:
  path = file_path(key)
  val = nil
  val = ::File.read(path) if ::File.exists?(path)
  return val
end

#set(key, value, expiry_time = configatron.cachetastic.defaults.default_expiry) ⇒ Object

get



33
34
35
36
37
38
# File 'lib/cachetastic/adapters/file.rb', line 33

def set(key, value, expiry_time = configatron.cachetastic.defaults.default_expiry) # :nodoc:
  so = Cachetastic::Cache::StoreObject.new(key, unmarshal(value), expiry_time.from_now)
  path = file_path(key)
  ::File.open(path, 'w') {|f| f.write marshal(so)}
  value
end

#transform_key(key) ⇒ Object

expire_all



53
54
55
# File 'lib/cachetastic/adapters/file.rb', line 53

def transform_key(key) # :nodoc:
  key.to_s.hexdigest
end