Class: EveOnline::Api::FileCache
- Inherits:
-
Object
- Object
- EveOnline::Api::FileCache
- Defined in:
- lib/eve_online/api/file_cache.rb
Instance Method Summary collapse
- #expiration_date(file_path) ⇒ Object
- #file_for(key) ⇒ Object
- #get(key) ⇒ Object
-
#initialize(options = {}) ⇒ FileCache
constructor
A new instance of FileCache.
- #set(key, data, expiration_date) ⇒ Object
Constructor Details
#initialize(options = {}) ⇒ FileCache
Returns a new instance of FileCache.
13 14 15 16 17 |
# File 'lib/eve_online/api/file_cache.rb', line 13 def initialize = {} self.directory = [:directory] || Dir.tmpdir self.logger = [:logger] || NullLogger.instance self.boundary = [:boundary] || '_FILE_CACHE_' end |
Instance Method Details
#expiration_date(file_path) ⇒ Object
66 67 68 69 70 71 72 73 74 75 |
# File 'lib/eve_online/api/file_cache.rb', line 66 def expiration_date file_path logger.debug "Finding expiration date from #{file_path}" file_name = File.basename file_path logger.debug "File name = #{file_name}" , _ = file_name.split %r{#{boundary}}, 2 logger.debug "Timestamp = #{}" time = Time.at .to_i logger.debug "Time = #{time}" time end |
#file_for(key) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/eve_online/api/file_cache.rb', line 41 def file_for key logger.debug "Finding cache instances for #{key}" hex = Digest::SHA1.hexdigest key.to_s pattern = File.join directory, "*#{boundary}#{hex}" logger.debug "Glob for #{pattern} on disk" files = Dir.glob pattern logger.debug "Found #{files.size} cache instances" return unless files.any? request_time = Time.now logger.debug "Excluding expired instanced" live = files.select { |file_name| expiration_date = expiration_date file_name expiration_date > request_time } logger.debug "Found #{live.size} live cache instances" return unless live.any? logger.debug "Selecting most recent live instance" instance = live.sort_by { |file_name| expiration_date file_name }[-1] expiration_date = expiration_date instance logger.debug "Instance is #{instance}, expires = #{expiration_date}" instance end |
#get(key) ⇒ Object
19 20 21 22 23 24 25 |
# File 'lib/eve_online/api/file_cache.rb', line 19 def get key logger.debug "Cache asked for #{key}" file = file_for key return unless file logger.debug "Reading from cache at #{file}" File.read file end |
#set(key, data, expiration_date) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/eve_online/api/file_cache.rb', line 27 def set key, data, expiration_date logger.debug "Asked to cache #{key} until #{expiration_date}" request_time = Time.now return unless expiration_date > request_time hex = Digest::SHA1.hexdigest key.to_s file_name = "#{expiration_date.to_i}#{boundary}#{hex}" file_path = File.join directory, file_name logger.debug "Realising cache instance as #{file_path}" File.open file_path, 'w' do |file| file.print data end logger.debug "Cached #{key} in #{file_path}" end |