Class: RestCore::Cache

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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



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

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

Class Method Details

.membersObject



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

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

Instance Method Details

#app_call(env) ⇒ Object



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

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



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

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



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

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

#call(env, &k) ⇒ Object



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

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