Class: YAMLCache
- Inherits:
-
Object
- Object
- YAMLCache
- Defined in:
- lib/yaml_cache.rb
Instance Method Summary collapse
- #cache(key, expiration, &block) ⇒ Object
-
#initialize(path) ⇒ YAMLCache
constructor
A new instance of YAMLCache.
- #read(key) ⇒ Object
- #write(key, value = nil, &block) ⇒ Object
Constructor Details
#initialize(path) ⇒ YAMLCache
Returns a new instance of YAMLCache.
4 5 6 7 |
# File 'lib/yaml_cache.rb', line 4 def initialize(path) @path = path @store = load_store end |
Instance Method Details
#cache(key, expiration, &block) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/yaml_cache.rb', line 18 def cache(key, expiration, &block) value = nil if @store.has_key?(key) if @store[key][:expiration] == nil || (@store[key][:expiration] - Time.now.to_i) <= 0 value = block.call store(key, value, expiration) else value = @store[key][:value] end else value = block.call store(key, value, expiration) end File.write(@path, @store.to_yaml) return value end |
#read(key) ⇒ Object
14 15 16 |
# File 'lib/yaml_cache.rb', line 14 def read(key) @store[key][:value] end |
#write(key, value = nil, &block) ⇒ Object
9 10 11 12 |
# File 'lib/yaml_cache.rb', line 9 def write(key, value=nil, &block) store(key, block ? block.call : value) File.write(@path, @store.to_yaml) end |