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

- (CacheFileStore) initialize(storage_path, serializer = Marshal)

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"



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

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

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

Instance Attribute Details

- (Object) serializer (readonly)

Returns the value of attribute serializer



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

def serializer
  @serializer
end

- (Object) storage_path (readonly)

Returns the value of attribute storage_path



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

def storage_path
  @storage_path
end

Instance Method Details

- (Object) clean



31
32
33
34
35
# File 'lib/common/cache_file_store.rb', line 31

def clean
  Dir[File.join(@storage_path, '*')].each do |f|
    File.delete(f) unless File.symlink?(f)
  end
end

- (Object) get_entry_file_path(key)



53
54
55
# File 'lib/common/cache_file_store.rb', line 53

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

- (Object) read_entry(key)



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

def read_entry(key)
  entry_file_path = get_entry_file_path(key)

  if File.exists?(entry_file_path)
    return @serializer.load(File.read(entry_file_path))
  end
end

- (Object) write_entry(key, data_to_store, cache_ttl)



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

def write_entry(key, data_to_store, cache_ttl)
  if cache_ttl > 0
    File.open(get_entry_file_path(key), 'w') do |f|
      f.write(@serializer.dump(data_to_store))
    end
  end
end