Class: Rack::APIMock

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/apimock.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, apidir: 'api') ⇒ APIMock

Returns a new instance of APIMock.



6
7
8
9
# File 'lib/rack/apimock.rb', line 6

def initialize(app, apidir: 'api')
  @app = app
  @apidir = apidir
end

Instance Method Details

#_call(env) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rack/apimock.rb', line 15

def _call(env)
  @status, @headers = 200, {}
  if env["CONTENT_TYPE"] =~ /application\/json/i
    @request_body = JSON.parse(env["rack.input"].gets) rescue nil
  end
  template_path = get_template_path(env)

  # Missing Template File
  return @app.call(env) unless template_path

  response = ERB.new(::File.open(template_path, &:read), nil, '<>').result(binding)

  unless env['QUERY_STRING'].empty?
    query_string = Rack::Utils.parse_nested_query(env['QUERY_STRING'])

    case env["CONTENT_TYPE"]
    when /application\/json/i
      data = JSON.parse(response)
      response = query_string.each_with_object({}) {|(key, _), new_hash|
        new_hash.merge!(key => data[key])
      }.to_json
    end
  end

  [@status, @headers, [response]]
end

#call(env) ⇒ Object



11
12
13
# File 'lib/rack/apimock.rb', line 11

def call(env)
  dup._call(env)
end