Class: CacheFileStore

Inherits:
Object
  • Object
show all
Defined in:
lib/common/cache_file_store.rb

Direct Known Subclasses

TyphoeusCache

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(storage_path, serializer = Marshal) ⇒ CacheFileStore

The serializer must have the 2 methods .load and .dump

(Marshal and YAML have them)

YAML is Human Readable, contrary to Marshal which store in a binary format Marshal does not need any “require”


21
22
23
24
25
26
27
28
29
30
31
# File 'lib/common/cache_file_store.rb', line 21

def initialize(storage_path, serializer = Marshal)
  @cache_dir    = File.expand_path(storage_path)
  @storage_path = File.expand_path(File.join(storage_path, storage_dir))
  @serializer   = serializer

  # File.directory? for ruby <= 1.9 otherwise,
  # it makes more sense to do Dir.exist? :/
  unless File.directory?(@storage_path)
    FileUtils.mkdir_p(@storage_path)
  end
end

Instance Attribute Details

#cache_dirObject (readonly)

Returns the value of attribute cache_dir


15
16
17
# File 'lib/common/cache_file_store.rb', line 15

def cache_dir
  @cache_dir
end

#serializerObject (readonly)

Returns the value of attribute serializer


15
16
17
# File 'lib/common/cache_file_store.rb', line 15

def serializer
  @serializer
end

#storage_pathObject (readonly)

Returns the value of attribute storage_path


15
16
17
# File 'lib/common/cache_file_store.rb', line 15

def storage_path
  @storage_path
end

Instance Method Details

#cleanObject


33
34
35
36
37
38
39
40
41
42
43
# File 'lib/common/cache_file_store.rb', line 33

def clean
  # clean old directories
  Dir[File.join(@cache_dir, '*')].each do |f|
    if File.directory?(f)
      # delete directory if create time is older than 4 hours
      FileUtils.rm_rf(f) if File.mtime(f) < (Time.now - (60*240))
    else
      File.delete(f) unless File.symlink?(f)
    end
  end
end

#get_entry_file_path(key) ⇒ Object


65
66
67
# File 'lib/common/cache_file_store.rb', line 65

def get_entry_file_path(key)
  File::join(@storage_path, key)
end

#read_entry(key) ⇒ Object


45
46
47
48
49
50
51
# File 'lib/common/cache_file_store.rb', line 45

def read_entry(key)
  begin
    @serializer.load(File.read(get_entry_file_path(key)))
  rescue
    nil
  end
end

#storage_dirObject


69
70
71
72
73
74
# File 'lib/common/cache_file_store.rb', line 69

def storage_dir
  time   = Time.now
  random = (0...8).map { (65 + rand(26)).chr }.join

  Digest::MD5.hexdigest("#{time}#{random}")
end

#write_entry(key, data_to_store, cache_ttl) ⇒ Object


53
54
55
56
57
58
59
60
61
62
63
# File 'lib/common/cache_file_store.rb', line 53

def write_entry(key, data_to_store, cache_ttl)
  if cache_ttl > 0
    File.open(get_entry_file_path(key), 'w') do |f|
      begin
        f.write(@serializer.dump(data_to_store))
      rescue
        nil # spec fix for "can't dump hash with default proc" when stub_request with  response headers
      end
    end
  end
end