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 (Constant) (defaults to: Marshal)


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

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.



7
8
9
# File 'lib/cms_scanner/cache/file_store.rb', line 7

def serializer
  @serializer
end

#storage_pathObject (readonly)

Returns the value of attribute storage_path.



7
8
9
# File 'lib/cms_scanner/cache/file_store.rb', line 7

def storage_path
  @storage_path
end

Instance Method Details

#cleanObject

TODO: rename this to clear ?



24
25
26
27
28
# File 'lib/cms_scanner/cache/file_store.rb', line 24

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)


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

def read_entry(key)
  return if expired_entry?(key)

  serializer.load(File.read(entry_path(key)))
rescue StandardError
  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.positive?

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