Class: Kamen::Middleware::MockRequest

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

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ MockRequest

Returns a new instance of MockRequest.



7
8
9
# File 'lib/kamen/middleware/mock_request.rb', line 7

def initialize app
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/kamen/middleware/mock_request.rb', line 11

def call env
  request = ActionDispatch::Request.new(env)

  Rails.application.routes.router.recognize(request) do |route, params|
    # params => {:controller=>"v1/users", :action=>"show", :id=>"1"}

    resp = ::Kamen::MockCache.find_mock_response(params)
    if resp[:read]  # source file is parsed
      unless resp[:data].nil? # cache hits, there is a mock data
        return [200, {}, [resp[:data]]]
      else # no mock data given, pass request to rails application
        # just skip this branch and exit block to call downstream middleware
      end
    else

      if ::Kamen::Parser.handle_source_file(params)

        # there is some data written in cache so we can load again.
        resp = ::Kamen::MockCache.find_mock_response(params)

        return [200, {}, [resp[:data]]] if resp[:read] && resp[:data]
      end
    end
  end

  @status, @headers, @response = @app.call(env)
  [@status, @headers, @response]
end