Class: CMSScanner::Cache::FileStore

Inherits:
Object
  • Object
show all
Defined in:
lib/cms_scanner/cache/file_store.rb

Overview

Cache Implementation using files

Direct Known Subclasses

Typhoeus

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(storage_path, serializer = Marshal) ⇒ FileStore

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”

Parameters:

  • storage_path (String)
  • serializer () (defaults to: Marshal)


14
15
16
17
18
19
# File 'lib/cms_scanner/cache/file_store.rb', line 14

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

  FileUtils.mkdir_p(@storage_path) unless Dir.exist?(@storage_path)
end

Instance Attribute Details

#serializerObject (readonly)

Returns the value of attribute serializer.



5
6
7
# File 'lib/cms_scanner/cache/file_store.rb', line 5

def serializer
  @serializer
end

#storage_pathObject (readonly)

Returns the value of attribute storage_path.



5
6
7
# File 'lib/cms_scanner/cache/file_store.rb', line 5

def storage_path
  @storage_path
end

Instance Method Details

#cleanObject

TODO: rename this to clear ?



22
23
24
25
26
# File 'lib/cms_scanner/cache/file_store.rb', line 22

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

#entry_expiration_path(key) ⇒ String

Returns The expiration file path associated to the key.

Parameters:

  • key (String)

Returns:

  • (String)

    The expiration file path associated to the key



61
62
63
# File 'lib/cms_scanner/cache/file_store.rb', line 61

def entry_expiration_path(key)
  entry_path(key) + '.expiration'
end

#entry_path(key) ⇒ String

Returns The file path associated to the key.

Parameters:

  • key (String)

Returns:

  • (String)

    The file path associated to the key



54
55
56
# File 'lib/cms_scanner/cache/file_store.rb', line 54

def entry_path(key)
  File.join(storage_path, key)
end

#read_entry(key) ⇒ Mixed

Parameters:

  • key (String)

Returns:

  • (Mixed)


31
32
33
34
35
36
37
38
39
# File 'lib/cms_scanner/cache/file_store.rb', line 31

def read_entry(key)
  file_path = entry_path(key)

  return if expired_entry?(key)

  serializer.load(File.read(file_path))
rescue
  nil
end

#write_entry(key, data_to_store, cache_ttl) ⇒ Object

Parameters:

  • key (String)
  • data_to_store (Mixed)
  • cache_ttl (Integer)


44
45
46
47
48
49
# File 'lib/cms_scanner/cache/file_store.rb', line 44

def write_entry(key, data_to_store, cache_ttl)
  return unless cache_ttl.to_i > 0

  File.write(entry_path(key), serializer.dump(data_to_store))
  File.write(entry_expiration_path(key), Time.now.to_i + cache_ttl)
end