Class: GrapeCache::Middleware

Inherits:
Grape::Middleware::Base
  • Object
show all
Defined in:
lib/grape_cache/middleware.rb

Overview

Middleware Class

Instance Method Summary collapse

Instance Method Details

#afterObject



28
29
30
31
32
33
34
35
36
37
# File 'lib/grape_cache/middleware.rb', line 28

def after
  # Check if cache is enabled in this route
  return unless cache?

  # Cache its output
  store.write key(@params), response, @options.fetch(:options, {}).merge(endpoint.options.fetch(:options, {}))

  # Do not change the return
  return
end

#beforeObject

Generate the cache if its necessary



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/grape_cache/middleware.rb', line 40

def before
  # Check if cache is enabled in this route
  return unless cache?

  # Generate the cache key
  k = key(params)

  # Check the current key exists in the cache
  return unless store.exist?(k)

  # Get to the response it
  res = MultiJson.load store.read(k)

  # Return in the Rack Formatt
  [res['status'], res['headers'], res['body']]
end

#call!(env) ⇒ Object

Overwriting the method call! from Grape::Middleware::Base Reason: Make the :before call to return the whole stack



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/grape_cache/middleware.rb', line 7

def call!(env)
  @env = env
  # Just here is moving!
  before_res = before
  return before_res unless before_res.nil?
  # end the overwrite
  @app_response = @app.call(@env)

  begin
    after_response = after
  rescue StandardError => e
    warn "caught error of type #{e.class} in after callback inside #{self.class.name} : #{e.message}"
    raise e
  end

  response = after_response || @app_response
  merge_headers response
  response
end