Class: Committee::RequestUnpacker

Inherits:
Object
  • Object
show all
Defined in:
lib/committee/request_unpacker.rb

Instance Method Summary collapse

Constructor Details

#initialize(request) ⇒ RequestUnpacker

Returns a new instance of RequestUnpacker.



3
4
5
# File 'lib/committee/request_unpacker.rb', line 3

def initialize(request)
  @request = request
end

Instance Method Details

#callObject



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/committee/request_unpacker.rb', line 7

def call
  if !@request.content_type || @request.content_type =~ %r{application/json}
    # if Content-Type is empty or JSON, and there was a request body, try
    # to interpret it as JSON
    if (body = @request.body.read).length != 0
      @request.body.rewind
      hash = MultiJson.decode(body)
      # We want a hash specifically. '42', 42, and [42] will all be
      # decoded properly, but we can't use them here.
      if !hash.is_a?(Hash)
        raise BadRequest,
          "Invalid JSON input. Require object with parameters as keys."
      end
      indifferent_params(hash)
    # if request body is empty, we just have empty params
    else
      {}
    end
  elsif @request.content_type == "application/x-www-form-urlencoded"
    # Actually, POST means anything in the request body, could be from
    # PUT or PATCH too. Silly Rack.
    indifferent_params(@request.POST)
  else
    raise BadRequest, "Unsupported Content-Type: #{@request.content_type}."
  end
end