Class: Codnar::Cache
- Inherits:
-
Object
- Object
- Codnar::Cache
- Defined in:
- lib/codnar/cache.rb
Overview
Cache long computations in disk files.
Instance Attribute Summary collapse
-
#force_recompute ⇒ Object
Whether to recompute values even if they are cached.
Instance Method Summary collapse
-
#cache_file(input) ⇒ Object
Return the file expected to cache the computed results for a given input,.
-
#cached_computation(input) ⇒ Object
Access the results of the computation for the specified input.
-
#initialize(directory, &block) ⇒ Cache
constructor
Connect to an existing disk cache.
-
#uncached_computation(input) ⇒ Object
Access the results of a computation for the specified input, in case we do not have a cache directory to look for and store the results in.
Constructor Details
#initialize(directory, &block) ⇒ Cache
Connect to an existing disk cache. The cache is expected to be stored in a directory of the specified name, which is either in the current working directory or in one of its parent directories.
12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/codnar/cache.rb', line 12 def initialize(directory, &block) @force_recompute = false @computation = block @directory = find_directory(Dir.pwd, directory) if @directory class <<self; alias [] :cached_computation; end else class <<self; alias [] :uncached_computation; end $stderr.puts("#{$0}: Could not find cache directory: #{directory}.") end end |
Instance Attribute Details
#force_recompute ⇒ Object
Whether to recompute values even if they are cached.
7 8 9 |
# File 'lib/codnar/cache.rb', line 7 def force_recompute @force_recompute end |
Instance Method Details
#cache_file(input) ⇒ Object
Return the file expected to cache the computed results for a given input,
36 37 38 39 |
# File 'lib/codnar/cache.rb', line 36 def cache_file(input) key = Digest.hexencode(Digest::SHA2.digest(input.to_yaml)) return @directory + "/" + key + ".yaml" end |
#cached_computation(input) ⇒ Object
Access the results of the computation for the specified input. Fetch the result from the cache if it is there, otherwise invoke the computation and store the result in the cache for the next time.
27 28 29 30 31 32 33 |
# File 'lib/codnar/cache.rb', line 27 def cached_computation(input) file = cache_file(input) return YAML.load_file(file) if File.exists?(file) and not @force_recompute result = @computation.call(input) File.open(file, "w") { |file| file.write(result.to_yaml) } return result end |
#uncached_computation(input) ⇒ Object
Access the results of a computation for the specified input, in case we do not have a cache directory to look for and store the results in.
43 44 45 |
# File 'lib/codnar/cache.rb', line 43 def uncached_computation(input) return @computation.call(input) end |