Class: Nanowrimo::Cache

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

Overview

Handles caching of WCAPI data

Constant Summary collapse

CACHE_FILE =
'./nano_cache'
DEFAULT_MAX_CACHE_AGE =

24 hours in seconds, defines when cached data expires.

(24*60*60)
@@cache_data =
{}
@@cache_mutex =
Mutex.new

Class Method Summary collapse

Class Method Details

.add_to_cache(type, key, data = []) ⇒ Object

Receives data that needs to be added to the cache



46
47
48
49
50
# File 'lib/nanowrimo/cache.rb', line 46

def self.add_to_cache type, key, data=[]
  @@cache_mutex.synchronize{
    @@cache_data["#{type}"] = {"#{key}" => Hash[:data, data, :created_at, Time.now]}
  }
end

.cache_dataObject



14
15
16
# File 'lib/nanowrimo/cache.rb', line 14

def self.cache_data
  @@cache_data
end

.cache_mutexObject



17
18
19
# File 'lib/nanowrimo/cache.rb', line 17

def self.cache_mutex
  @@cache_mutex
end

.clear_cacheObject

Clears all cache from memory, will of course write that out to disk



53
54
55
# File 'lib/nanowrimo/cache.rb', line 53

def self.clear_cache
  @@cache_data.clear
end

.find_data(type, key) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/nanowrimo/cache.rb', line 28

def self.find_data(type, key)
  @@cache_mutex.synchronize {
    return nil unless @@cache_data["#{type}"]
    return nil unless @@cache_data["#{type}"]["#{key}"]
    if Time.now - @@cache_data["#{type}"]["#{key}"][:created_at] < DEFAULT_MAX_CACHE_AGE
      @@cache_data["#{type}"]["#{key}"][:data]
    end
  }
end

.load_cacheObject

Load the cached data into memory from disk.



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

def self.load_cache
  if File.exist?(CACHE_FILE)
    @@cache_data = YAML::load(File.read(CACHE_FILE))
  end
end

.save_cache_to_diskObject

For when the cache needs to be not in memory anymore.



39
40
41
42
43
# File 'lib/nanowrimo/cache.rb', line 39

def self.save_cache_to_disk
  File.open(CACHE_FILE, 'w') do |out|
    YAML.dump(@@cache_data, out)
  end
end