lib/taskjuggler/DataCache.rb in taskjuggler-0.2.0 vs lib/taskjuggler/DataCache.rb in taskjuggler-0.2.1
- old
+ new
@@ -75,62 +75,27 @@
# but all data values are lost.
def flush
@entries = {}
end
- # Store _value_ into the cache using _key_ to tag it. _key_ must be unique
- # and must be used to load the value from the cache again. You cannot
- # store nil values!
- def store(value, key)
- @stores += 1
-
- if @entries.size > @highWaterMark
- while @entries.size > @lowWaterMark
- # How many entries do we need to delete to get to the low watermark?
- toDelete = @entries.size - @lowWaterMark
- @entries.delete_if do |foo, e|
- # Hit counts age with every cleanup.
- (e.hits -= 1) < 0 && (toDelete -= 1) >= 0
- end
- end
- end
-
- @entries[key] = DataCacheEntry.new(value)
-
- value
- end
-
if RUBY_VERSION < '1.9.0'
# Ruby 1.8 has a buggy hash key generation algorithm that leads to many
# hash collisions. We completely disable caching on 1.8.
- def load(key)
- nil
- end
-
- def cached(key)
+ def cached(*args)
yield
end
else
- # Retrieve the value indexed by _key_ from the cache. If it's not found,
- # nil is returned.
- def load(key)
- if (e = @entries[key])
- @hits += 1
- e.value
- else
- @misses += 1
- nil
- end
- end
-
- # If we have a value for the _key_, return the value. Otherwise call the
+ # _args_ is a set of arguments that unambigously identify the data entry.
+ # It's converted into a hash to store or recover a previously stored
+ # entry. If we have a value for the key, return the value. Otherwise call the
# block to compute the value, store it and return it.
- def cached(key)
+ def cached(*args)
+ key = args.hash
if @entries.has_key?(key)
e = @entries[key]
@hits += 1
e.value
else
@@ -145,9 +110,33 @@
<<"EOT"
Entries: #{@entries.size} Stores: #{@stores}
Hits: #{@hits} Misses: #{@misses}
Hit Rate: #{@hits * 100.0 / (@hits + @misses)}%
EOT
+ end
+
+ private
+
+ # Store _value_ into the cache using _key_ to tag it. _key_ must be unique
+ # and must be used to load the value from the cache again. You cannot
+ # store nil values!
+ def store(value, key)
+ @stores += 1
+
+ if @entries.size > @highWaterMark
+ while @entries.size > @lowWaterMark
+ # How many entries do we need to delete to get to the low watermark?
+ toDelete = @entries.size - @lowWaterMark
+ @entries.delete_if do |foo, e|
+ # Hit counts age with every cleanup.
+ (e.hits -= 1) < 0 && (toDelete -= 1) >= 0
+ end
+ end
+ end
+
+ @entries[key] = DataCacheEntry.new(value)
+
+ value
end
end
end