module MyPrecious::DataCaching

Public Class Methods

print_error_info(target) { || ... } click to toggle source

Private Instance Methods

apply_cache(cache, &get_data) click to toggle source

Use cached data in or write data to a file cache

cache should be a Pathname to a file in which JSON data or can be cached.

The block given will only be invoked if the cache does not exist or is stale. The block must return JSON.dump -able data.

# File lib/myprecious/data_caches.rb, line 36
def apply_cache(cache, &get_data)
  cache = Pathname(cache)
  if !MyPrecious.caching_disabled && cache.exist? && cache.stat.mtime > Time.now - ONE_DAY
    return cache.open('r') {|inf| JSON.load(inf)}
  else
    # Short-circuit to error if we've already received one for filling this cache
    if @data_cache_errors_fetching && @data_cache_errors_fetching[cache]
      raise @data_cache_errors_fetching[cache]
    end
    
    result = begin
      DataCaching.print_error_info(cache.basename('.json'), &get_data)
    rescue StandardError => e
      # Remember this error in case there is another attempt to fill this cache
      (@data_cache_errors_fetching ||= {})[cache] = e
      raise
    end
    
    cache.dirname.mkpath
    cache.open('w') {|outf| JSON.dump(result, outf)}
    return result
  end
end