Class: Inq::Cacheable

Inherits:
Object
  • Object
show all
Defined in:
lib/inq/cacheable.rb

Overview

Class for use in caching expensive operations

Defined Under Namespace

Modules: MarshalCache

Instance Method Summary collapse

Constructor Details

#initialize(config, start_date, end_date, tmpdir = Dir.mktmpdir) ⇒ Cacheable

Returns a new instance of Cacheable.



9
10
11
12
13
14
# File 'lib/inq/cacheable.rb', line 9

def initialize(config, start_date, end_date, tmpdir = Dir.mktmpdir)
  @config = config
  @start_date = start_date
  @end_date = end_date
  @tmpdir = tmpdir
end

Instance Method Details

#cached(key, extra_digest = nil) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/inq/cacheable.rb', line 16

def cached(key, extra_digest = nil)
  cache = @config["cache"]
  return yield if cache.nil?

  hash_key = []
  hash_key << Digest::SHA1.hexdigest(extra_digest) if extra_digest
  hash_key << Digest::SHA1.hexdigest(@config.to_json)
  cache_key = File.join(@start_date, @end_date, key, hash_key.join("-"))

  case cache["type"]
  when "marshal"
    MarshalCache.cached(cache_key, @tmpdir) { yield }
  when "self"
    # Can provide your own cache in Inq.new
    # e.g.
    # cache_mechanism = ->(cache_key, config, block) do
    #   if cached?
    #     cached_value
    #   else
    #     block.call
    #   end
    # end
    # Inq.new("owner/repo", date, cache_mechanism)
    cache["cache_mechanism"].call(cache_key, @config, ->() { yield })
  end
end