Class: Exchange::Cache::File

Inherits:
Base
  • Object
show all
Defined in:
lib/exchange/cache/file.rb

Overview

Note:

This is not a recommended caching option

A class that allows to store api call results in files. It just may be necessary to cache large files somewhere, this class allows you to do that

Author:

  • Beat Richartz

Since:

  • 0.3

Version:

  • 0.6

Instance Method Summary collapse

Instance Method Details

#cached(api, opts = {}) { ... } ⇒ Object

returns either cached data from a stored file or stores a file. This method has to be the same in all the cache classes in order for the configuration binding to work

Parameters:

  • api (Exchange::ExternalAPI::Subclass)

    The API class the data has to be stored for

  • opts (Hash) (defaults to: {})

    the options to cache with

Options Hash (opts):

  • :at (Time)

    IS IGNORED FOR FILECACHE

  • :cache_period (Symbol)

    The period to cache the file for

Yields:

  • This method takes a mandatory block with an arity of 0 and calls it if no cached result is available

Raises:

Since:

  • 0.3



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/exchange/cache/file.rb', line 24

def cached api, opts={}, &block
  raise_caching_needs_block! unless block_given?
  
  today = Time.now
  dir   = config.path
  path  = ::File.join(dir, key(api, opts[:cache_period]))
  
  if ::File.exists?(path)
    result = opts[:plain] ? ::File.read(path) : ::File.read(path).decachify
  else
    result = super
    if result && !result.to_s.empty?
      make_sure_exists dir
      clean!           dir, api
      
      ::File.open(path, 'w') {|f| f.write(result.cachify) }
    end
  end
  
  result
end