Class: TheCity::JsonCache
- Inherits:
-
CacheAdapter
- Object
- CacheAdapter
- TheCity::JsonCache
- Defined in:
- lib/cachers/file/json_cache.rb
Overview
This class caches the data in a JSON file.
Instance Method Summary collapse
-
#expire_cache!(key) ⇒ Object
Expire the cache.
-
#get_cache_file(key) ⇒ Object
Get the file name where the cache is stored.
-
#get_data(key) ⇒ Object
Get the data from the cache.
-
#initialize ⇒ JsonCache
constructor
Constructor.
-
#is_cache_expired?(key) ⇒ Boolean
Check if the cache has expired.
-
#save_data(key, data, expire_in = nil) ⇒ Object
Save data to the cache.
Constructor Details
#initialize ⇒ JsonCache
Constructor.
13 14 15 16 |
# File 'lib/cachers/file/json_cache.rb', line 13 def initialize() super @cache_dir = THECITY_STORAGE_DIR + subdomain + '/'; end |
Instance Method Details
#expire_cache!(key) ⇒ Object
Expire the cache.
74 75 76 77 78 79 80 81 82 83 |
# File 'lib/cachers/file/json_cache.rb', line 74 def expire_cache!(key) file = _find_file_key(key) unless file.nil? begin File.unlink(@cache_dir + file) rescue raise new Exception("Unable to remove cache file: $file") end end end |
#get_cache_file(key) ⇒ Object
Get the file name where the cache is stored.
50 51 52 |
# File 'lib/cachers/file/json_cache.rb', line 50 def get_cache_file(key) _find_file_key(key) end |
#get_data(key) ⇒ Object
Get the data from the cache.
60 61 62 63 64 65 66 |
# File 'lib/cachers/file/json_cache.rb', line 60 def get_data(key) filename = _find_file_key(key) return nil if filename.nil? file = File.open(@cache_dir + filename, "rb") contents = file.read return Marshal.load(contents) end |
#is_cache_expired?(key) ⇒ Boolean
Check if the cache has expired.
91 92 93 94 95 96 97 98 99 100 101 102 |
# File 'lib/cachers/file/json_cache.rb', line 91 def is_cache_expired?(key) time_stamp_position = 1; fname = _find_file_key(key) return true if fname.nil? fname_a = fname.split('-') if Time.now.to_i > fname_a[time_stamp_position].to_i return true end return false; end |
#save_data(key, data, expire_in = nil) ⇒ Object
Save data to the cache.
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/cachers/file/json_cache.rb', line 26 def save_data(key, data, expire_in = nil) expire_in = 3600 if expire_in.nil? # 3600 seconds = 1 hour expire_in += Time.now.to_i _create_cache_directory_if_needed expire_cache!(key) filename = "#{key}-#{expire_in}-json.cache" begin File.open(@cache_dir + filename, 'w') {|f| f.write( Marshal.dump(data) ) } rescue return 'Unable to write to file' end return true end |