Class: RestCore::Cache

Inherits:
Object
  • Object
show all
Includes:
Middleware
Defined in:
lib/rest-core/middleware/cache.rb

Constant Summary

Constant Summary

Constants included from Middleware

Middleware::UNRESERVED

Constants included from RestCore

ASYNC, CLIENT, DRY, FAIL, HIJACK, LOG, PROMISE, REQUEST_HEADERS, REQUEST_METHOD, REQUEST_PATH, REQUEST_PAYLOAD, REQUEST_QUERY, REQUEST_URI, RESPONSE_BODY, RESPONSE_HEADERS, RESPONSE_KEY, RESPONSE_SOCKET, RESPONSE_STATUS, TIMER, Universal, VERSION

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Middleware

contain_binary?, #error_callback, escape, #fail, #give_promise, #id, included, #log, merge_hash, percent_encode, request_uri, #run, string_keys

Methods included from RestCore

eagerload, id

Constructor Details

#initialize(app, cache, expires_in, &block) ⇒ Cache

Returns a new instance of Cache



11
12
13
14
# File 'lib/rest-core/middleware/cache.rb', line 11

def initialize app, cache, expires_in, &block
  super(&block)
  @app, @cache, @expires_in = app, cache, expires_in
end

Class Method Details

.membersObject



8
# File 'lib/rest-core/middleware/cache.rb', line 8

def self.members; [:cache, :expires_in]; end

Instance Method Details

#app_call(env) ⇒ Object



29
30
31
32
33
34
35
36
37
# File 'lib/rest-core/middleware/cache.rb', line 29

def app_call env
  app.call(env) do |res|
    yield(if (res[FAIL] || []).empty?
            cache_for(res)
          else
            res
          end)
  end
end

#cache_get(env, &k) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/rest-core/middleware/cache.rb', line 44

def cache_get env, &k
  return unless cache(env)
  return unless cache_for?(env)

  uri = request_uri(env)
  start_time = Time.now
  return unless data = cache(env)[cache_key(env)]
  res = log(env.merge(REQUEST_URI => uri),
            Event::CacheHit.new(Time.now - start_time, uri))
  data_extract(data, res, k)
end

#cache_key(env) ⇒ Object



39
40
41
42
# File 'lib/rest-core/middleware/cache.rb', line 39

def cache_key env
  "rest-core:cache:#{Digest::MD5.hexdigest(env['cache.key'] ||
                                           cache_key_raw(env))}"
end

#call(env, &k) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/rest-core/middleware/cache.rb', line 16

def call env, &k
  e = if env['cache.update']
        cache_clear(env)
      else
        env
      end

  cache_get(e){ |cached|
    e[TIMER].cancel if e[TIMER]
    k.call(cached)
  } || app_call(e, &k)
end