Module: SimpleFileCache

Defined in:
lib/simple_file_cache.rb

Defined Under Namespace

Classes: Configuration

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.configurationObject

Returns the value of attribute configuration.



33
34
35
# File 'lib/simple_file_cache.rb', line 33

def configuration
  @configuration
end

Class Method Details

.configure {|configuration| ... } ⇒ Object

Yields:



44
45
46
# File 'lib/simple_file_cache.rb', line 44

def self.configure
  yield(configuration)
end

.load_or_recompute(cache_file_name, &block) ⇒ Object

Check whether a cache file exists and is recent (last modified today). If so, read the file using Marshal#load and return it. Otherwise, execute the given block to obtain the new data, save to the cache file using Marshal#dump and return the updated data.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/simple_file_cache.rb', line 9

def self.load_or_recompute(cache_file_name, &block)
  if cache_file_name.include?('/')
    cache_file_pathname = cache_file_name
  else
    cache_file_pathname = "#{configuration.cache_dir_path}/#{cache_file_name}"
  end

  cache_file_is_recent = file_is_recent?(cache_file_pathname)
  rails_production_env = defined?(Rails) && Rails.env.production?
  use_cached_copy = cache_file_is_recent && !rails_production_env

  if use_cached_copy
    log "File '#{cache_file_pathname}' exists and is recent. Using cached file."
    cache_file_contents = File.binread(cache_file_pathname)
    return Marshal.load(cache_file_contents)
  else
    log "File '#{cache_file_pathname}' inexistent or out of date. Creating new cache file."
    data_to_cache = block.call
    File.binwrite(cache_file_pathname, Marshal.dump(data_to_cache))
    return data_to_cache
  end
end

.resetObject



40
41
42
# File 'lib/simple_file_cache.rb', line 40

def self.reset
  @configuration = Configuration.new
end