lib/zache.rb in zache-0.10.1 vs lib/zache.rb in zache-0.11.0

- old
+ new

@@ -94,17 +94,17 @@ # # If the <tt>dirty</tt> argument is set to <tt>true</tt>, a previously # calculated result will be returned if it exists and is already expired. def get(key, lifetime: 2**32, dirty: false) if block_given? - if (dirty || @dirty) && locked? && key_expired?(key) && @hash.key?(key) + if (dirty || @dirty) && locked? && expired?(key) && @hash.key?(key) return @hash[key][:value] end synchronized { calc(key, lifetime) { yield } } else rec = @hash[key] - if key_expired?(key) + if expired?(key) return rec[:value] if dirty || @dirty @hash.delete(key) rec = nil end raise 'The key is absent in the cache' if rec.nil? @@ -115,17 +115,24 @@ # Checks whether the value exists in the cache by the provided key. Returns # TRUE if the value is here. If the key is already expired in the hash, # it will be removed by this method and the result will be FALSE. def exists?(key, dirty: false) rec = @hash[key] - if key_expired?(key) && !dirty && !@dirty + if expired?(key) && !dirty && !@dirty @hash.delete(key) rec = nil end !rec.nil? end + # Checks whether the key exists in the cache and is expired. If the + # key is absent FALSE is returned. + def expired?(key) + rec = @hash[key] + !rec.nil? && rec[:start] < Time.now - rec[:lifetime] + end + # Returns the modification time of the key, if it exists. # If not, current time is returned. def mtime(key) rec = @hash[key] rec.nil? ? Time.now : rec[:start] @@ -158,18 +165,18 @@ synchronized { @hash = {} } end # Remove keys that are expired. def clean - synchronized { @hash.delete_if { |_key, value| key_expired?(value) } } + synchronized { @hash.delete_if { |_key, value| expired?(value) } } end private def calc(key, lifetime) rec = @hash[key] - rec = nil if key_expired?(key) + rec = nil if expired?(key) if rec.nil? @hash[key] = { value: yield, start: Time.now, lifetime: lifetime @@ -188,12 +195,7 @@ yield end else yield end - end - - def key_expired?(key) - rec = @hash[key] - !rec.nil? && rec[:start] < Time.now - rec[:lifetime] end end