Class: Kennel::FileCache
- Inherits:
-
Object
- Object
- Kennel::FileCache
- Defined in:
- lib/kennel/file_cache.rb
Instance Method Summary collapse
- #fetch(key, version) ⇒ Object
-
#initialize(file) ⇒ FileCache
constructor
A new instance of FileCache.
- #persist ⇒ Object
Constructor Details
#initialize(file) ⇒ FileCache
Returns a new instance of FileCache.
8 9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/kennel/file_cache.rb', line 8 def initialize(file) @file = file @data = begin Marshal.load(File.read(@file)) # rubocop:disable Security/MarshalLoad rescue StandardError {} end @now = Time.now.to_i @expires = @now + (30 * 24 * 60 * 60) # 1 month @data.reject! { |_, (_, _, ex)| ex < @now } # expire old data end |
Instance Method Details
#fetch(key, version) ⇒ Object
21 22 23 24 25 26 27 28 |
# File 'lib/kennel/file_cache.rb', line 21 def fetch(key, version) old_value, old_version = @data[key] return old_value if old_version == version new_value = yield @data[key] = [new_value, version, @expires] new_value end |
#persist ⇒ Object
30 31 32 33 |
# File 'lib/kennel/file_cache.rb', line 30 def persist FileUtils.mkdir_p(File.dirname(@file)) File.write(@file, Marshal.dump(@data)) end |