Class: Dandy::Request

Inherits:
Object
  • Object
show all
Includes:
Hypo::Scope
Defined in:
lib/dandy/request.rb

Instance Method Summary collapse

Constructor Details

#initialize(route_matcher, container, chain_factory, view_factory) ⇒ Request

Returns a new instance of Request.



12
13
14
15
16
17
# File 'lib/dandy/request.rb', line 12

def initialize(route_matcher, container, chain_factory, view_factory)
  @container = container
  @route_matcher = route_matcher
  @chain_factory = chain_factory
  @view_factory = view_factory
end

Instance Method Details

#handle(rack_env) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/dandy/request.rb', line 19

def handle(rack_env)
  create_scope

  path = rack_env['PATH_INFO']
  request_method = rack_env['REQUEST_METHOD']
  match = @route_matcher.match(path, request_method)

  headers = Hash[
    *rack_env.select {|k, v| k.start_with? 'HTTP_'}
       .collect {|k, v| [k.sub(/^HTTP_/, ''), v]}
       .collect {|k, v| [k.split('_').collect(&:capitalize).join('-'), v]}
       .flatten
  ]
  register_params(headers, :dandy_headers)

  if match.nil?
    result = [404, {'Content-Type' => headers['Accept']}, []]
  else
    query = Rack::Utils.parse_nested_query(rack_env['QUERY_STRING']).to_snake_keys.symbolize_keys
    register_params(query, :dandy_query)

    data = rack_env['rack.parser.result'] ? rack_env['rack.parser.result'].to_snake_keys.deep_symbolize_keys! : nil
    register_params(data, :dandy_data)

    chain = @chain_factory.create(match)
    chain_result = chain.execute

    if match.route.view
      body = @view_factory.create(match.route.view, headers['Accept'], {keys_format: headers['Keys-Format'] || 'snake'})
    else
      if chain_result.is_a?(String)
        body = chain_result
      else # generate JSON when nothing other is requested
        if headers['Keys-Format'] == 'camel' && chain_result.is_a?(Hash)
          chain_result = chain_result.to_camelback_keys
        end

        body = JSON.generate(chain_result)
      end
    end

    status = @container.resolve(:dandy_status)
    result = [status, {'Content-Type' => headers['Accept']}, [body]]
  end

  release

  result
end