Class: Downgrade::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/downgrade/middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



4
5
6
# File 'lib/downgrade/middleware.rb', line 4

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



8
9
10
11
12
13
14
15
16
# File 'lib/downgrade/middleware.rb', line 8

def call(env)
  if Downgrade.middleware_switch.is_on?
    middleware_cache(env)
  elsif Downgrade.path_switch.is_on?
    path_cache(env)
  else
    @app.call(env)
  end
end

#middleware_cache(env) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/downgrade/middleware.rb', line 18

def middleware_cache(env)
  req = Rack::Request.new(env)
  if req.get?
    Downgrade.cache_store.fetch(request_cache_key(req), expires_in: 10.minutes) do
      status, headers, rackbody = @app.call(env)
      [status, headers, [rackbody.body]]
    end
  else
    @app.call(env)
  end
end

#path_cache(env) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/downgrade/middleware.rb', line 30

def path_cache(env)
  req = Rack::Request.new(env)
  if req.get?
    if Downgrade::Path.hit_regexp?(req.path)
      Downgrade.cache_store.fetch(request_cache_key(req), expires_in: 10.minutes) do
        status, headers, rackbody = @app.call(env)
        [status, headers, [rackbody.body]]
      end
    else
      @app.call(env)
    end
  else
    @app.call(env)
  end
end

#request_cache_key(req) ⇒ Object



46
47
48
# File 'lib/downgrade/middleware.rb', line 46

def request_cache_key(req)
  "downgrade:middleware:#{req.path}:#{req['HTTP_AUTHORIZATION']}"
end