Class: RestCore::Cache

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

Constant Summary

Constant Summary

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

Constants included from Middleware

Middleware::UNRESERVED

Instance Attribute Summary

Attributes included from Wrapper

#default_engine, #middles, #wrapped

Class Method Summary (collapse)

Instance Method Summary (collapse)

Methods included from Wrapper

included, #members, partial_deep_copy, #run, #to_app, #use

Methods included from RestCore

eagerload, id

Methods included from Middleware

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

Constructor Details

- (Cache) initialize(app, cache, expires_in, &block)



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

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

Class Method Details

+ (Object) members



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

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

Instance Method Details

- (Object) cache_get(env, &k)



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

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)]
  log(env, Event::CacheHit.new(Time.now - start_time, uri)).
    merge(data_extract(data, env.merge(REQUEST_URI => uri), k))
end

- (Object) cache_key(env)



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

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

- (Object) call(env, &k)



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/rest-core/middleware/cache.rb', line 18

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]
    wrapped.call(cached, &k)
  } || app.call(e){ |res|
         wrapped.call(res){ |res_wrapped|
           k.call(if (res_wrapped[FAIL] || []).empty?
                    cache_for(res).merge(res_wrapped)
                  else
                    res_wrapped
                  end)}}
end