class Amazon::Search::Cache
This class is used internally by Ruby/Amazon. You should never need to manually instantiate it or invoke most of the methods here. The only exceptions are flush_all and flush_expired.
Constants
- MAX_AGE
Age in days below which to consider cache files valid.
Public Class Methods
new(path)
click to toggle source
# File lib/amazon/search/cache.rb, line 27 def initialize(path) ::FileUtils::mkdir_p(path) unless File.exists?(path) unless File.directory?(path) raise PathError, "cache path #{path} is not a directory" end unless File.readable?(path) raise PathError, "cache path #{path} is not readable" end unless File.writable?(path) raise PathError, "cache path #{path} is not writable" end @path = path end
Public Instance Methods
cache(url, contents)
click to toggle source
Cache the data from contents and associate it with url.
# File lib/amazon/search/cache.rb, line 73 def cache(url, contents) digest = Digest::MD5.hexdigest(url) cache_file = File.join(@path, digest) Amazon::dprintf("Caching %s...\n", digest) File.open(cache_file, 'w') { |f| f.puts contents } end
cached?(url)
click to toggle source
Determine whether or not the the response to a given URL is cached. Returns
true
or false
.
# File lib/amazon/search/cache.rb, line 48 def cached?(url) digest = Digest::MD5.hexdigest(url) cache_files = Dir.glob(File.join(@path, '*')).map do |d| File.basename(d) end return cache_files.include?(digest) && (Time.now - File.mtime(File.join(@path, digest))) / ONE_DAY <= MAX_AGE end
flush_all()
click to toggle source
This method flushes all files from the cache directory specified in the object's @path variable.
# File lib/amazon/search/cache.rb, line 85 def flush_all FileUtils.rm Dir.glob(File.join(@path, '*')) end
flush_expired()
click to toggle source
This method flushes expired files from the cache directory specified in the object's @path variable.
# File lib/amazon/search/cache.rb, line 92 def flush_expired expired_files = Dir.glob(File.join(@path, '*')).find_all do |f| (now - File.mtime(f)) / ONE_DAY > MAX_AGE end FileUtils.rm expired_files end
get_cached(url)
click to toggle source
Retrieve the cached response associated with url.
# File lib/amazon/search/cache.rb, line 61 def get_cached(url) digest = Digest::MD5.hexdigest(url) cache_file = File.join(@path, digest) return nil unless File.exist? cache_file Amazon::dprintf("Fetching %s from cache...\n", digest) File.open(File.join(cache_file)).readlines.to_s end